From be1f661b71073a215894928e5d44bf98829f7331 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sat, 12 Oct 2019 17:44:09 +0800 Subject: [PATCH 01/24] update deps before publish --- packages/utils/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/utils/package.json b/packages/utils/package.json index 404c0f70..a78cdf29 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -59,7 +59,7 @@ "compileEnhancements": false }, "dependencies": { - "jsonql-constants": "^1.8.3", + "jsonql-constants": "^1.8.4", "jsonql-errors": "^1.1.3", "lodash-es": "^4.17.15" }, -- Gitee From 4e022cffaef98aaa9d775ecd410a0bece3218b3f Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 13 Oct 2019 14:13:51 +0800 Subject: [PATCH 02/24] remapping the top interface --- packages/ws-client/package.json | 4 ++-- packages/ws-client/src/main.js | 26 ++++++++++++++++++++++--- packages/ws-client/src/options/index.js | 11 +++++------ packages/ws-client/src/utils/helpers.js | 15 ++------------ 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index 56cac0e7..1ad20a01 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -52,11 +52,11 @@ }, "dependencies": { "esm": "^3.2.25", - "jsonql-constants": "^1.8.3", + "jsonql-constants": "^1.8.4", "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.2", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.7.4", + "jsonql-utils": "^0.7.5", "nb-event-service": "^1.8.3" }, "devDependencies": { diff --git a/packages/ws-client/src/main.js b/packages/ws-client/src/main.js index 14059c47..22143ae4 100644 --- a/packages/ws-client/src/main.js +++ b/packages/ws-client/src/main.js @@ -3,11 +3,31 @@ // any kind of clients /** - * @param {object} opts configuration @NOTE we expect the contract to be part of the options + * @param {object} opts configuration @NOTE we expect the contract and eventEmitter to be part of the opts * @param {object} socketClient we normalize the auth and non auth client from now on * @return {object} the wsClient instance with all the available API */ export default function wsClient(opts, socketClient) { - - + const { eventEmitter } = opts; + // we need to inject property to this client later + // therefore we need to do it this way + const _wsClient = (opts) => ( + checkOptions(opts) + .then(opts => ({ + opts, + nspMap: processContract(opts) + ee: eventEmitter || new ee() + })) + .then( + ({opts, nspMap, ee}) => createSocketClient(opts, nspMap, ee, socketClient) + ) + // @TODO the generator should be part of the http client + .then( + ({opts, nspMap, ee}) => generator(opts, nspMap, ee) + ) + .catch(err => { + console.error(`jsonql-ws-client init error`, err) + }) + ) + return injectToFn(_wsClient, 'CLIENT_TYPE_INFO', opts.serverType) } diff --git a/packages/ws-client/src/options/index.js b/packages/ws-client/src/options/index.js index 39d72a2c..58eb1225 100644 --- a/packages/ws-client/src/options/index.js +++ b/packages/ws-client/src/options/index.js @@ -23,13 +23,12 @@ import { import { SOCKET_IO, WS, AVAILABLE_SERVERS } from './constants' import { getDebug } from '../utils' const debug = getDebug('check-options') - - - +// constant props const constProps = { - // this will be the switcher! + eventEmitter: null, + // we unify the two different client into one now + // only expect different parameter nspClient: null, - nspAuthClient: null, // contructed path wssPath: '' } @@ -38,7 +37,7 @@ const defaultOptions = { loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]), logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]), // we will use this for determine the socket.io client type as well - useJwt: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE]), + useJwt: createConfig(true, [BOOLEAN_TYPE, STRING_TYPE]), hostname: createConfig(false, [STRING_TYPE]), namespace: createConfig(JSONQL_PATH, [STRING_TYPE]), wsOptions: createConfig({transports: ['websocket'], 'force new connection' : true}, [OBJECT_TYPE]), diff --git a/packages/ws-client/src/utils/helpers.js b/packages/ws-client/src/utils/helpers.js index e0e1a644..72f62007 100644 --- a/packages/ws-client/src/utils/helpers.js +++ b/packages/ws-client/src/utils/helpers.js @@ -1,13 +1,10 @@ // group all the small functions here -import { - QUERY_ARG_NAME, - JS_WS_SOCKET_IO_NAME -} from 'jsonql-constants' +import { JS_WS_SOCKET_IO_NAME, JS_WS_NAME} from 'jsonql-constants' // we shouldn't do this anymore export const fixWss = (url, serverType) => { // ws only allow ws:// path - if (serverType === WS) { + if (serverType === JS_WS_NAME) { return url.replace('http://', 'ws://') } return url; @@ -37,14 +34,6 @@ export const clearMainEmitEvt = (ee, namespace) => { }) } -/** - * @param {*} args arguments to send - *@return {object} formatted payload - */ -export const formatPayload = (args) => ( - { [QUERY_ARG_NAME]: args } -) - /** * @param {object} nsps namespace as key * @param {string} type of server -- Gitee From 48f0ea36c1537192f30c3ea439f5e73235c08570 Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 13 Oct 2019 15:18:33 +0800 Subject: [PATCH 03/24] have to relook at the old code to decided what to do next, because the jsonql-ws-client should be just deal with the basic structure and have to be very generic, then import the client specific parts from respective client to form the complete socket client --- .../src/core/client-event-handler.js | 6 +- packages/ws-client/src/core/generator.js | 7 +- .../ws-client/src/core/map-event-to-client.js | 122 ++++++++++++++++++ packages/ws-client/src/main.js | 4 + packages/ws-client/src/utils/index.js | 9 +- 5 files changed, 134 insertions(+), 14 deletions(-) create mode 100644 packages/ws-client/src/core/map-event-to-client.js diff --git a/packages/ws-client/src/core/client-event-handler.js b/packages/ws-client/src/core/client-event-handler.js index ef3ede42..4a37e69d 100644 --- a/packages/ws-client/src/core/client-event-handler.js +++ b/packages/ws-client/src/core/client-event-handler.js @@ -7,7 +7,7 @@ import { EMIT_EVT, SOCKET_IO, WS -} from './utils/constants' +} from '../options/constants' import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, @@ -15,8 +15,8 @@ import { ERROR_PROP_NAME } from 'jsonql-constants' -import { getDebug, createEvt, clearMainEmitEvt } from './utils' -import triggerNamespacesOnError from './utils/trigger-namespaces-on-error' +import { getDebug, createEvt, clearMainEmitEvt } from '../utils' +import triggerNamespacesOnError from './trigger-namespaces-on-error' const debugFn = getDebug('client-event-handler') /** diff --git a/packages/ws-client/src/core/generator.js b/packages/ws-client/src/core/generator.js index ef752d04..974b9dba 100644 --- a/packages/ws-client/src/core/generator.js +++ b/packages/ws-client/src/core/generator.js @@ -30,10 +30,11 @@ import { READY_PROP_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants' -const { injectToFn, objDefineProps } from 'jsonql-utils' +import { injectToFn, objDefineProps } from 'jsonql-utils' + +import { getDebug, createEvt, toArray } from '../utils' +import { EMIT_EVT, NOT_ALLOW_OP, UNKNOWN_RESULT, MY_NAMESPACE } from '../options/constants' -import { getDebug, constants, createEvt, toArray } from './utils' -const { EMIT_EVT, NOT_ALLOW_OP, UNKNOWN_RESULT, MY_NAMESPACE } = constants; const debugFn = getDebug('generator') /** diff --git a/packages/ws-client/src/core/map-event-to-client.js b/packages/ws-client/src/core/map-event-to-client.js new file mode 100644 index 00000000..f64c3a41 --- /dev/null +++ b/packages/ws-client/src/core/map-event-to-client.js @@ -0,0 +1,122 @@ +// this was call create-client in the old code + +// this will create the socket.io client +import { chainPromises } from 'jsonql-jwt' +import { getNameFromPayload, isString } from 'jsonql-params-validator' +import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants' + +import { nspClient, nspAuthClient } from '../utils/create-nsp-client' +import clientEventHandler from '../client-event-handler' +import ioMainHandler from './io-main-handler' + +import { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils' +const debugFn = getDebug('io-create-client') + +// just to make it less ugly +const mapNsps = (nsps, namespaces) => nsps + .map((nsp, i) => ({[namespaces[i]]: nsp})) + .reduce((last, next) => Object.assign(last,next), {}) + +/** + * This one will run the create nsps in sequence and make sure + * the auth one connect before we call the others + * @param {object} opts configuration + * @param {object} nspMap contract map + * @param {string} token validation + * @return {object} promise resolve with namespaces, nsps in same order array + */ +const createAuthNsps = function(opts, nspMap, token, namespaces) { + let { publicNamespace } = nspMap; + opts.token = token; + // @TODO seems that we still need to create two seperate type of clients + let p1 = () => nspAuthClient(namespaces[0], opts) + let p2 = () => nspClient(namespaces[1], opts) + return chainPromises([p1(), p2()]) + .then(nsps => ({ + nsps: mapNsps(nsps, namespaces), + namespaces, + login: false + })) +} + +/** + * Because the nsps can be throw away so it doesn't matter the scope + * this will get reuse again + * @param {object} opts configuration + * @param {object} nspMap from contract + * @param {string|null} token whether we have the token at run time + * @return {object} nsps namespace with namespace as key + */ +const createNsps = function(opts, nspMap, token) { + let { nspSet, publicNamespace } = nspMap; + let login = false; + let nsps = {} + // first we need to binding all the events handler + if (opts.enableAuth && opts.useJwt) { + let namespaces = getNamespaceInOrder(nspSet, publicNamespace) + debugFn('namespaces', namespaces) + login = opts.useJwt; // just saying we need to listen to login event + if (token) { + debugFn('call createAuthNsps') + return createAuthNsps(opts, nspMap, token, namespaces) + } + debugFn('init with a placeholder') + return nspClient(publicNamespace, opts) + .then(nsp => ({ + nsps: { + [ publicNamespace ]: nsp, + [ namespaces[0] ]: false + }, + namespaces, + login + })) + } + // standard without login + // the stock version should not have a namespace + return nspClient(false, opts) + .then(nsp => ({ + nsps: {[publicNamespace]: nsp}, + namespaces: [publicNamespace], + login + })) +} + +/** + * This is just copy of the ws version we need to figure + * out how to deal with the roundtrip login later + * @param {object} opts configuration + * @param {object} nspMap namespace with resolvers + * @param {object} ee EventEmitter to pass through + * @return {object} what comes in what goes out + */ +export default function createClient(opts, nspMap, ee) { + // arguments don't change + let args = [opts, nspMap, ee, ioMainHandler] + return createNsps(opts, nspMap, opts.token) + .then( ({ nsps, namespaces, login }) => { + // binding the listeners - and it will listen to LOGOUT event + // to unbind itself, and the above call will bind it again + Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])) + if (login) { + ee.$only(LOGIN_EVENT_NAME, function(token) { + // here we should disconnect all the previous nsps + disconnect(nsps) + // first trigger a LOGOUT event to unbind ee to ws + // ee.$trigger(LOGOUT_EVENT_NAME) // <-- this seems to cause a lot of problems + clearMainEmitEvt(ee, namespaces) + debugFn('LOGIN_EVENT_NAME') + createNsps(opts, nspMap, token) + .then(newNsps => { + // rebind it + Reflect.apply( + clientEventHandler, + null, + args.concat([newNsps.namespaces, newNsps.nsps]) + ) + }) + }) + } + // return this will also works because the outter call are in promise chain + return { opts, nspMap, ee } + }) +} diff --git a/packages/ws-client/src/main.js b/packages/ws-client/src/main.js index 22143ae4..d210edec 100644 --- a/packages/ws-client/src/main.js +++ b/packages/ws-client/src/main.js @@ -1,7 +1,11 @@ // the top level API // The goal is to create a generic method that will able to handle // any kind of clients +import createSocketClient from './core/create-socket-client' +import generator from './core/generator' +import checkOptions from './options' +import { ee, processContract } from './utils' /** * @param {object} opts configuration @NOTE we expect the contract and eventEmitter to be part of the opts * @param {object} socketClient we normalize the auth and non auth client from now on diff --git a/packages/ws-client/src/utils/index.js b/packages/ws-client/src/utils/index.js index 15017704..31dc4508 100644 --- a/packages/ws-client/src/utils/index.js +++ b/packages/ws-client/src/utils/index.js @@ -1,9 +1,6 @@ // export the util methods -import getNamespaceInOrder from './get-namespace-in-order' -import checkOptions from './check-options' import ee from './ee' -import * as constants from './constants' import getDebug from './get-debug' import processContract from './process-contract' @@ -11,16 +8,12 @@ import { isArray } from 'jsonql-params-validator' // moved to jsonql-utils import { toArray, createEvt } from 'jsonql-utils' - - - +// export export { - getNamespaceInOrder, createEvt, clearMainEmitEvt, checkOptions, ee, - constants, getDebug, processContract, toArray, -- Gitee From a0af5cbbc0b25d26e7b05e17f091b3e9fe1630aa Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 13 Oct 2019 19:02:13 +0800 Subject: [PATCH 04/24] add the beta client for reference --- packages/ws-client/beta/index.js | 5 + packages/ws-client/beta/main.js | 6 + .../beta/src/client-event-handler.js | 91 + .../beta/src/create-socket-client.js | 23 + packages/ws-client/beta/src/generator.js | 298 + .../ws-client/beta/src/io/create-client.js | 121 + packages/ws-client/beta/src/io/index.js | 6 + .../ws-client/beta/src/io/io-main-handler.js | 102 + packages/ws-client/beta/src/main.js | 45 + .../beta/src/node/client-generator.js | 42 + packages/ws-client/beta/src/node/main.cjs.js | 7544 ++++++++++++++++ .../ws-client/beta/src/utils/check-options.js | 66 + .../beta/src/utils/client-generator.js | 46 + .../ws-client/beta/src/utils/constants.js | 49 + .../beta/src/utils/create-nsp-client.js | 34 + packages/ws-client/beta/src/utils/ee.js | 14 + .../ws-client/beta/src/utils/get-debug.js | 22 + .../beta/src/utils/get-namespace-in-order.js | 20 + packages/ws-client/beta/src/utils/index.js | 74 + .../beta/src/utils/process-contract.js | 41 + .../src/utils/trigger-namespaces-on-error.js | 15 + .../ws-client/beta/src/ws/create-client.js | 85 + .../beta/src/ws/extract-ws-payload.js | 43 + packages/ws-client/beta/src/ws/index.js | 5 + .../ws-client/beta/src/ws/ws-main-handler.js | 116 + packages/ws-client/beta/src/ws/ws.js | 16 + packages/ws-client/dist/jsonql-ws-client.js | 7866 ----------------- .../ws-client/dist/jsonql-ws-client.js.map | 1 - packages/ws-server/package.json | 1 + 29 files changed, 8930 insertions(+), 7867 deletions(-) create mode 100644 packages/ws-client/beta/index.js create mode 100644 packages/ws-client/beta/main.js create mode 100644 packages/ws-client/beta/src/client-event-handler.js create mode 100644 packages/ws-client/beta/src/create-socket-client.js create mode 100644 packages/ws-client/beta/src/generator.js create mode 100644 packages/ws-client/beta/src/io/create-client.js create mode 100644 packages/ws-client/beta/src/io/index.js create mode 100644 packages/ws-client/beta/src/io/io-main-handler.js create mode 100644 packages/ws-client/beta/src/main.js create mode 100644 packages/ws-client/beta/src/node/client-generator.js create mode 100644 packages/ws-client/beta/src/node/main.cjs.js create mode 100644 packages/ws-client/beta/src/utils/check-options.js create mode 100644 packages/ws-client/beta/src/utils/client-generator.js create mode 100644 packages/ws-client/beta/src/utils/constants.js create mode 100644 packages/ws-client/beta/src/utils/create-nsp-client.js create mode 100644 packages/ws-client/beta/src/utils/ee.js create mode 100644 packages/ws-client/beta/src/utils/get-debug.js create mode 100644 packages/ws-client/beta/src/utils/get-namespace-in-order.js create mode 100644 packages/ws-client/beta/src/utils/index.js create mode 100644 packages/ws-client/beta/src/utils/process-contract.js create mode 100644 packages/ws-client/beta/src/utils/trigger-namespaces-on-error.js create mode 100644 packages/ws-client/beta/src/ws/create-client.js create mode 100644 packages/ws-client/beta/src/ws/extract-ws-payload.js create mode 100644 packages/ws-client/beta/src/ws/index.js create mode 100644 packages/ws-client/beta/src/ws/ws-main-handler.js create mode 100644 packages/ws-client/beta/src/ws/ws.js delete mode 100644 packages/ws-client/dist/jsonql-ws-client.js delete mode 100644 packages/ws-client/dist/jsonql-ws-client.js.map diff --git a/packages/ws-client/beta/index.js b/packages/ws-client/beta/index.js new file mode 100644 index 00000000..934b4c00 --- /dev/null +++ b/packages/ws-client/beta/index.js @@ -0,0 +1,5 @@ +// This is the module entry point +import clientGenerator from './src/utils/client-generator' +import main from './src/main' + +export default main(clientGenerator) diff --git a/packages/ws-client/beta/main.js b/packages/ws-client/beta/main.js new file mode 100644 index 00000000..d8bb48a4 --- /dev/null +++ b/packages/ws-client/beta/main.js @@ -0,0 +1,6 @@ +// the node client main interface +const main = require('./src/node/main.cjs') +const clientGenerator = require('./src/node/client-generator') + +// finally export it +module.exports = main(clientGenerator) diff --git a/packages/ws-client/beta/src/client-event-handler.js b/packages/ws-client/beta/src/client-event-handler.js new file mode 100644 index 00000000..ef3ede42 --- /dev/null +++ b/packages/ws-client/beta/src/client-event-handler.js @@ -0,0 +1,91 @@ +// @TODO port what is in the ws-main-handler +// because all the client side call are via the ee +// and that makes it re-usable between different client setup +import { + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + EMIT_EVT, + SOCKET_IO, + WS +} from './utils/constants' +import { + LOGIN_EVENT_NAME, + LOGOUT_EVENT_NAME, + NOT_LOGIN_ERR_MSG, + ERROR_PROP_NAME +} from 'jsonql-constants' + +import { getDebug, createEvt, clearMainEmitEvt } from './utils' +import triggerNamespacesOnError from './utils/trigger-namespaces-on-error' +const debugFn = getDebug('client-event-handler') + +/** + * A fake ee handler + * @param {string} namespace nsp + * @param {object} ee EventEmitter + * @return {void} + */ +const notLoginWsHandler = (namespace, ee) => { + ee.$only( + createEvt(namespace, EMIT_EVT), + function(resolverName, args) { + debugFn('noLoginHandler hijack the ws call', namespace, resolverName, args) + let error = { + message: NOT_LOGIN_ERR_MSG + } + // It should just throw error here and should not call the result + // because that's channel for handling normal event not the fake one + ee.$call(createEvt(namespace, resolverName, ERROR_PROP_NAME), [error]) + // also trigger the result handler, but wrap inside the error key + ee.$call(createEvt(namespace, resolverName, RESULT_PROP_NAME), [{ error }]) + } + ) +} + +/** + * centralize all the comm in one place + * @param {object} opts configuration + * @param {array} namespaces namespace(s) + * @param {object} ee Event Emitter instance + * @param {function} bindWsHandler binding the ee to ws + * @param {array} namespaces array of namespace available + * @param {object} nsps namespaced nsp + * @return {void} nothing + */ +export default function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) { + // loop + // @BUG for io this has to be in order the one with auth need to get call first + // The order of login is very import we need to run a waterfall here to make sure + // one is execute then the other + namespaces.forEach(namespace => { + if (nsps[namespace]) { + debugFn('call bindWsHandler', namespace) + let args = [namespace, nsps[namespace], ee] + if (opts.serverType === SOCKET_IO) { + let { nspSet } = nspMap; + args.push(nspSet[namespace]) + args.push(opts) + } + Reflect.apply(bindWsHandler, null, args) + } else { + // a dummy placeholder + notLoginWsHandler(namespace, ee) + } + }) + // this will be available regardless enableAuth + // because the server can log the client out + ee.$on(LOGOUT_EVENT_NAME, function() { + debugFn('LOGOUT_EVENT_NAME') + // disconnect(nsps, opts.serverType) + // we need to issue error to all the namespace onError handler + triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME) + // rebind all of the handler to the fake one + namespaces.forEach( namespace => { + clearMainEmitEvt(ee, namespace) + // clear out the nsp + nsps[namespace] = false; + // add a NOT LOGIN error if call + notLoginWsHandler(namespace, ee) + }) + }) +} diff --git a/packages/ws-client/beta/src/create-socket-client.js b/packages/ws-client/beta/src/create-socket-client.js new file mode 100644 index 00000000..08429459 --- /dev/null +++ b/packages/ws-client/beta/src/create-socket-client.js @@ -0,0 +1,23 @@ +import { JsonqlError } from 'jsonql-errors' + +import createWsClient from './ws' +import createIoClient from './io' + +import { SOCKET_IO, WS, SOCKET_NOT_DEFINE_ERR } from './utils/constants' + +/** + * get the create client instance function + * @param {string} type of client + * @return {function} the actual methods + * @public + */ +export default function createSocketClient(opts, nspMap, ee) { + switch (opts.serverType) { + case SOCKET_IO: + return createIoClient(opts, nspMap, ee) + case WS: + return createWsClient(opts, nspMap, ee) + default: + throw new JsonqlError(SOCKET_NOT_DEFINE_ERR) + } +} diff --git a/packages/ws-client/beta/src/generator.js b/packages/ws-client/beta/src/generator.js new file mode 100644 index 00000000..72ad566a --- /dev/null +++ b/packages/ws-client/beta/src/generator.js @@ -0,0 +1,298 @@ +// generator resolvers +// this will be a mini client server architect +// The reason is when the enableAuth setup - the private route +// might not be validated, but we need the callable point is ready +// therefore this part will always take the contract and generate +// callable api for the developer to setup their front end +// the only thing is - when they call they might get an error or +// NOT_LOGIN_IN and they can react to this error accordingly +import { + JsonqlResolverNotFoundError, + JsonqlValidationError, + JsonqlError, + finalCatch +} from 'jsonql-errors' +import { + validateAsync, + validateSync, + isKeyInObject, + isString +} from 'jsonql-params-validator' +import { + ERROR_TYPE, + DATA_KEY, + ERROR_KEY, + ERROR_PROP_NAME, + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + SEND_MSG_PROP_NAME, + LOGIN_EVENT_NAME, + READY_PROP_NAME, + LOGOUT_EVENT_NAME +} from 'jsonql-constants' +import { getDebug, constants, createEvt, toArray } from './utils' +const { EMIT_EVT, NOT_ALLOW_OP, UNKNOWN_RESULT, MY_NAMESPACE } = constants; +const debugFn = getDebug('generator') + +/** + * prepare the methods + * @param {object} opts configuration + * @param {object} nspMap resolvers index by their namespace + * @param {object} ee EventEmitter + * @return {object} of resolvers + * @public + */ +export default function generator(opts, nspMap, ee) { + const obj = {}; + const { nspSet } = nspMap; + for (let namespace in nspSet) { + let list = nspSet[namespace] + for (let resolverName in list) { + let params = list[resolverName] + let fn = createResolver(ee, namespace, resolverName, params) + obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee) + } + } + // add error handler + createNamespaceErrorHandler(obj, ee, nspSet) + // add onReady handler + createOnReadyhandler(obj, ee, nspSet) + // Auth related methods + createAuthMethods(obj, ee, opts) + // this is a helper method for the developer to know the namespace inside + obj.getNsp = () => { + return Object.keys(nspSet) + } + // output + return obj; +} + +/** + * create the actual function to send message to server + * @param {object} ee EventEmitter instance + * @param {string} namespace this resolver end point + * @param {string} resolverName name of resolver as event name + * @param {object} params from contract + * @return {function} resolver + */ +function createResolver(ee, namespace, resolverName, params) { + // note we pass the new withResult=true option + return function(...args) { + return validateAsync(args, params.params, true) + .then( _args => actionCall(ee, namespace, resolverName, _args) ) + .catch(finalCatch) + } +} + +/** + * just wrapper + * @param {object} ee EventEmitter + * @param {string} namespace where this belongs + * @param {string} resolverName resolver + * @param {array} args arguments + * @return {void} nothing + */ +function actionCall(ee, namespace, resolverName, args = []) { + debugFn(`actionCall: ${namespace} ${resolverName}`, args) + ee.$trigger(createEvt(namespace, EMIT_EVT), [ + resolverName, + toArray(args) + ]) +} + +/** + * break out to use in different places to handle the return from server + * @param {object} data from server + * @param {function} resolver from promise + * @param {function} rejecter from promise + * @return {void} nothing + */ +function respondHandler(data, resolver, rejecter) { + if (isKeyInObject(data, 'error')) { + debugFn('rejecter called', data.error) + rejecter(data.error) + } else if (isKeyInObject(data, 'data')) { + debugFn('resolver called', data.data) + resolver(data.data) + } else { + debugFn('UNKNOWN_RESULT', data) + rejecter({message: UNKNOWN_RESULT, error: data}) + } +} + +/** + * Add extra property to the resolver + * @param {string} namespace where this belongs + * @param {string} resolverName name as event name + * @param {object} params from contract + * @param {function} fn resolver function + * @param {object} ee EventEmitter + * @return {function} resolver + */ +const setupResolver = (namespace, resolverName, params, fn, ee) => { + // also need to setup a getter to get back the namespace of this resolver + if (Object.getOwnPropertyDescriptor(fn, MY_NAMESPACE) === undefined) { + Object.defineProperty(fn, MY_NAMESPACE, { + value: namespace, + writeable: false + }) + } + // onResult handler + if (Object.getOwnPropertyDescriptor(fn, RESULT_PROP_NAME) === undefined) { + Object.defineProperty(fn, RESULT_PROP_NAME, { + set: function(resultCallback) { + if (typeof resultCallback === 'function') { + ee.$only( + createEvt(namespace, resolverName, RESULT_PROP_NAME), + function resultHandler(result) { + respondHandler(result, resultCallback, (error) => { + ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error) + }) + } + ) + } + }, + get: function() { + return null; + } + }) + } + // we do need to add the send prop back because it's the only way to deal with + // bi-directional data stream + if (Object.getOwnPropertyDescriptor(fn, MESSAGE_PROP_NAME) === undefined) { + Object.defineProperty(fn, MESSAGE_PROP_NAME, { + set: function(messageCallback) { + // we expect this to be a function + if (typeof messageCallback === 'function') { + // did that add to the callback + let onMessageCallback = (args) => { + respondHandler(args, messageCallback, (error) => { + ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error) + }) + } + // register the handler for this message event + ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback) + } + }, + get: function() { + return null; // just return nothing + } + }) + } + // add an ERROR_PROP_NAME handler + if (Object.getOwnPropertyDescriptor(fn, ERROR_PROP_NAME) === undefined) { + Object.defineProperty(fn, ERROR_PROP_NAME, { + set: function(resolverErrorHandler) { + if (typeof resolverErrorHandler === 'function') { + // please note ERROR_PROP_NAME can add multiple listners + ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler) + } + }, + get: function() { + return null; + } + }) + } + // pairing with the server vesrion SEND_MSG_PROP_NAME + if (Object.getOwnPropertyDescriptor(fn, SEND_MSG_PROP_NAME) === undefined) { + Object.defineProperty(fn, SEND_MSG_PROP_NAME, { + set: function(messagePayload) { + const result = validateSync(toArray(messagePayload), params.params, true) + // here is the different we don't throw erro instead we trigger an + // onError + if (result[ERROR_KEY] && result[ERROR_KEY].length) { + ee.$call( + createEvt(namespace, resolverName, ERROR_PROP_NAME), + [JsonqlValidationError(resolverName, result[ERROR_KEY])] + ) + } else { + // there is no return only an action call + actionCall(ee, namespace, resolverName, result[DATA_KEY]) + } + }, + get: function() { + return null; // just return nothing + } + }) + } + return fn; +} + +/** + * The problem is the namespace can have more than one + * and we only have on onError message + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} nspSet namespace keys + * @return {void} + */ +const createNamespaceErrorHandler = (obj, ee, nspSet) => { + // using the onError as name + // @TODO we should follow the convention earlier + // make this a setter for the obj itself + if (Object.getOwnPropertyDescriptor(obj, ERROR_PROP_NAME) === undefined) { + Object.defineProperty(obj, ERROR_PROP_NAME, { + set: function(namespaceErrorHandler) { + if (typeof namespaceErrorHandler === 'function') { + // please note ERROR_PROP_NAME can add multiple listners + for (let namespace in nspSet) { + // this one is very tricky, we need to make sure the trigger is calling + // with the namespace as well as the error + ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler) + } + } + }, + get: function() { + return null; + } + }) + } +} + +/** + * This event will fire when the socket.io.on('connection') and ws.onopen + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} nspSet namespace keys + * @return {void} + */ +const createOnReadyhandler = (obj, ee, nspSet) => { + if (Object.getOwnPropertyDescriptor(obj, READY_PROP_NAME) === undefined) { + Object.defineProperty(obj, READY_PROP_NAME, { + set: function(onReadyCallback) { + if (typeof onReadyCallback === 'function') { + // reduce it down to just one flat level + let result = ee.$on(READY_PROP_NAME, onReadyCallback) + } + }, + get: function() { + return null; + } + }) + } +} + +/** + * Create auth related methods + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} opts configuration + * @return {void} + */ +const createAuthMethods = (obj, ee, opts) => { + if (opts.enableAuth) { + // create an additonal login handler + // we require the token + obj[opts.loginHandlerName] = (token) => { + debugFn(opts.loginHandlerName, token) + if (token && isString(token)) { + return ee.$trigger(LOGIN_EVENT_NAME, [token]) + } + throw new JsonqlValidationError(opts.loginHandlerName) + } + // logout event handler + obj[opts.logoutHandlerName] = (...args) => { + ee.$trigger(LOGOUT_EVENT_NAME, args) + } + } +} diff --git a/packages/ws-client/beta/src/io/create-client.js b/packages/ws-client/beta/src/io/create-client.js new file mode 100644 index 00000000..a8986f5d --- /dev/null +++ b/packages/ws-client/beta/src/io/create-client.js @@ -0,0 +1,121 @@ +// this will create the socket.io client +import { chainPromises } from 'jsonql-jwt' +import { getNameFromPayload, isString } from 'jsonql-params-validator' +import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants' + +import { nspClient, nspAuthClient } from '../utils/create-nsp-client' +import clientEventHandler from '../client-event-handler' +import ioMainHandler from './io-main-handler' + +import { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils' +const debugFn = getDebug('io-create-client') + +// just to make it less ugly +const mapNsps = (nsps, namespaces) => nsps + .map((nsp, i) => ({[namespaces[i]]: nsp})) + .reduce((last, next) => Object.assign(last,next), {}) + +/** + * This one will run the create nsps in sequence and make sure + * the auth one connect before we call the others + * @param {object} opts configuration + * @param {object} nspMap contract map + * @param {string} token validation + * @return {object} promise resolve with namespaces, nsps in same order array + */ +const createAuthNsps = function(opts, nspMap, token, namespaces) { + let { publicNamespace } = nspMap; + opts.token = token; + let p1 = () => nspAuthClient(namespaces[0], opts) + let p2 = () => nspClient(namespaces[1], opts) + return chainPromises([p1(), p2()]) + .then(nsps => ({ + nsps: mapNsps(nsps, namespaces), + namespaces, + login: false + })) +} + +/** + * Because the nsps can be throw away so it doesn't matter the scope + * this will get reuse again + * @param {object} opts configuration + * @param {object} nspMap from contract + * @param {string|null} token whether we have the token at run time + * @return {object} nsps namespace with namespace as key + */ +const createNsps = function(opts, nspMap, token) { + let { nspSet, publicNamespace } = nspMap; + let login = false; + let nsps = {} + // first we need to binding all the events handler + if (opts.enableAuth && opts.useJwt) { + let namespaces = getNamespaceInOrder(nspSet, publicNamespace) + debugFn('namespaces', namespaces) + login = opts.useJwt; // just saying we need to listen to login event + if (token) { + debugFn('call createAuthNsps') + return createAuthNsps(opts, nspMap, token, namespaces) + } + debugFn('init with a placeholder') + return nspClient(publicNamespace, opts) + .then(nsp => ({ + nsps: { + [ publicNamespace ]: nsp, + [ namespaces[0] ]: false + }, + namespaces, + login + })) + } + // standard without login + // the stock version should not have a namespace + return nspClient(false, opts) + .then(nsp => ({ + nsps: {[publicNamespace]: nsp}, + namespaces: [publicNamespace], + login + })) +} + + + +/** + * This is just copy of the ws version we need to figure + * out how to deal with the roundtrip login later + * @param {object} opts configuration + * @param {object} nspMap namespace with resolvers + * @param {object} ee EventEmitter to pass through + * @return {object} what comes in what goes out + */ +export default function createClient(opts, nspMap, ee) { + // arguments don't change + let args = [opts, nspMap, ee, ioMainHandler] + return createNsps(opts, nspMap, opts.token) + .then( ({ nsps, namespaces, login }) => { + // binding the listeners - and it will listen to LOGOUT event + // to unbind itself, and the above call will bind it again + Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])) + if (login) { + ee.$only(LOGIN_EVENT_NAME, function(token) { + // here we should disconnect all the previous nsps + disconnect(nsps) + // first trigger a LOGOUT event to unbind ee to ws + // ee.$trigger(LOGOUT_EVENT_NAME) // <-- this seems to cause a lot of problems + clearMainEmitEvt(ee, namespaces) + debugFn('LOGIN_EVENT_NAME') + createNsps(opts, nspMap, token) + .then(newNsps => { + // rebind it + Reflect.apply( + clientEventHandler, + null, + args.concat([newNsps.namespaces, newNsps.nsps]) + ) + }) + }) + } + // return this will also works because the outter call are in promise chain + return { opts, nspMap, ee } + }) +} diff --git a/packages/ws-client/beta/src/io/index.js b/packages/ws-client/beta/src/io/index.js new file mode 100644 index 00000000..d3ce1af0 --- /dev/null +++ b/packages/ws-client/beta/src/io/index.js @@ -0,0 +1,6 @@ + +// import socketIoMainHandler from './socketio-main-handler'; + +import createClient from './create-client' + +export default createClient diff --git a/packages/ws-client/beta/src/io/io-main-handler.js b/packages/ws-client/beta/src/io/io-main-handler.js new file mode 100644 index 00000000..72d088b5 --- /dev/null +++ b/packages/ws-client/beta/src/io/io-main-handler.js @@ -0,0 +1,102 @@ +import { + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + EMIT_EVT +} from '../utils/constants' +import { + ERROR_PROP_NAME, + LOGOUT_EVENT_NAME, + ERROR_TYPE, + ERROR_KEY, + DATA_KEY, + READY_PROP_NAME +} from 'jsonql-constants' +import { isKeyInObject } from 'jsonql-params-validator' +import { getDebug, createEvt, formatPayload } from '../utils' + +const debugFn = getDebug('io-main-handler') + +/** + * @param {object} ee Event Emitter + * @param {string} namespace namespace of this nsp + * @param {string} resolverName resolver to handle this call + * @return {function} capture the result + */ +const resultHandler = (ee, namespace, resolverName, evt = RESULT_PROP_NAME) => { + return (result) => { + ee.$trigger(createEvt(namespace, resolverName, evt), [result]) + } +} + +/** + * @param {object} nspSet resolver list + * @param {object} nsp nsp instance + * @param {object} ee Event Emitter + * @param {string} namespace name of this nsp + * @return {void} + */ +const createResolverListener = (nspSet, nsp, ee, namespace) => { + for (let resolverName in nspSet) { + nsp.on( + resolverName, + resultHandler(ee, namespace, resolverName, MESSAGE_PROP_NAME) + ) + } +} + +/** + * @param {object} nsp instance + * @param {object} ee Event Emitter + * @param {string} namespace name of this nsp + * @return {void} + */ +const mainEventHandler = (nsp, ee, namespace) => { + ee.$only( + createEvt(namespace, EMIT_EVT), + function resolverEmitHandler(resolverName, args) { + debugFn('mainEventHandler', resolverName, args) + nsp.emit( + resolverName, + formatPayload(args), + resultHandler(ee, namespace, resolverName) + ) + } + ) +} + +/** + * it makes no different at this point if we know its connection establish or not + * We should actually know this before hand before we call here + * @param {string} namespace of this client + * @param {object} socket this is the resolved nsp connection object + * @param {object} ee Event Emitter + * @param {object} nspSet the list of resolvers + * @param {object} opts configuration + */ +export default function ioMainHandler(namespace, socket, ee, nspSet, opts) { + // the main listener for all the client resolvers + mainEventHandler(socket, ee, namespace) + // it doesn't make much different between inside the connect or not + // loop through to create the listeners + createResolverListener(nspSet, socket, ee, namespace) + //@TODO next we need to add a ERROR handler + // The server side is not implementing a global ERROR call yet + // and the result or message error will be handle individually by their callback + // listen to the server close event + socket.on('disconnect', function disconnect() { + debugFn('io.disconnect') + // TBC what to do with this + // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) + }) + // listen to the logout event + ee.$on(LOGOUT_EVENT_NAME, function logoutHandler() { + try { + debugFn('terminate ws connection') + socket.close() + } catch(e) { + debugFn('terminate ws error', e) + } + }) + // the last one to fire + ee.$trigger(READY_PROP_NAME, namespace) +} diff --git a/packages/ws-client/beta/src/main.js b/packages/ws-client/beta/src/main.js new file mode 100644 index 00000000..ae6ae912 --- /dev/null +++ b/packages/ws-client/beta/src/main.js @@ -0,0 +1,45 @@ +// main api to get the ws-client + +import createSocketClient from './create-socket-client' +import generator from './generator' + +import { checkOptions, ee, processContract } from './utils' + +/** + * The main interface to create the wsClient for use + * @param {function} clientGenerator this is an internal way to generate node or browser client + * @return {function} wsClient + * @public + */ +export default function main(clientGenerator) { + /** + * @param {object} config configuration + * @param {object} [eventEmitter=false] this will be the bridge between clients + * @return {object} wsClient + */ + const wsClient = (config, eventEmitter = false) => { + return checkOptions(config) + .then(opts => ({ + opts, + nspMap: processContract(opts), + ee: eventEmitter || new ee() + }) + ) + .then(clientGenerator) + .then( + ({ opts, nspMap, ee }) => createSocketClient(opts, nspMap, ee) + ) + .then( + ({ opts, nspMap, ee }) => generator(opts, nspMap, ee) + ) + .catch(err => { + console.error('jsonql-ws-client init error', err) + }) + } + // use the Object.addProperty trick + Object.defineProperty(wsClient, 'CLIENT_TYPE_INFO', { + value: '__PLACEHOLDER__', + writable: false + }) + return wsClient; +} diff --git a/packages/ws-client/beta/src/node/client-generator.js b/packages/ws-client/beta/src/node/client-generator.js new file mode 100644 index 00000000..be382fc5 --- /dev/null +++ b/packages/ws-client/beta/src/node/client-generator.js @@ -0,0 +1,42 @@ +// client generator for node.js +const { + socketIoNodeHandshakeLogin, + socketIoNodeRoundtripLogin, + socketIoNodeClientAsync, + chainPromises, + wsNodeClient, + wsNodeAuthClient +} = require('jsonql-jwt') +const { JsonqlError } = require('jsonql-errors') +const { JS_WS_SOCKET_IO_NAME, JS_WS_NAME } = require('jsonql-constants') +const { isString } = require('jsonql-params-validator') +const debug = require('debug')('jsonql-ws-client:client-generator:cjs') + +/** + * websocket client generator + * @param {object} payload with opts, nspMap, ee + * @return {object} same just mutate it + */ +const clientGenerator = ({ opts, nspMap, ee }) => { + // debug(nspMap) + switch (opts.serverType) { + case JS_WS_SOCKET_IO_NAME: + // the socket.io normal client is not Promise so we make them all the same + opts.nspClient = socketIoNodeClientAsync; + // (...args) => Promise.resolve(Reflect.apply(socketIoNodeClient, null, args)) + // we also need to determine the type of socket.io login here + opts.nspAuthClient = isString(opts.useJwt) ? socketIoNodeRoundtripLogin : socketIoNodeHandshakeLogin; + // debug(opts.nspAuthClient) + break; + case JS_WS_NAME: + opts.nspClient = wsNodeClient; + opts.nspAuthClient = wsNodeAuthClient; + break; + default: + throw new JsonqlError(`Unknown serverType: ${opts.serverType}`) + } + return { opts, nspMap, ee } +} + +// export it +module.exports = clientGenerator; diff --git a/packages/ws-client/beta/src/node/main.cjs.js b/packages/ws-client/beta/src/node/main.cjs.js new file mode 100644 index 00000000..b8b7ad9f --- /dev/null +++ b/packages/ws-client/beta/src/node/main.cjs.js @@ -0,0 +1,7544 @@ +'use strict'; + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var debug$2 = _interopDefault(require('debug')); + +/** + * This is a custom error to throw when server throw a 406 + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var Jsonql406Error = /*@__PURE__*/(function (Error) { + function Jsonql406Error() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + // We can't access the static name from an instance + // but we can do it like this + this.className = Jsonql406Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql406Error); + } + } + + if ( Error ) Jsonql406Error.__proto__ = Error; + Jsonql406Error.prototype = Object.create( Error && Error.prototype ); + Jsonql406Error.prototype.constructor = Jsonql406Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 406; + }; + + staticAccessors.name.get = function () { + return 'Jsonql406Error'; + }; + + Object.defineProperties( Jsonql406Error, staticAccessors ); + + return Jsonql406Error; +}(Error)); + +/** + * This is a custom error to throw when server throw a 500 + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var Jsonql500Error = /*@__PURE__*/(function (Error) { + function Jsonql500Error() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = Jsonql500Error.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, Jsonql500Error); + } + } + + if ( Error ) Jsonql500Error.__proto__ = Error; + Jsonql500Error.prototype = Object.create( Error && Error.prototype ); + Jsonql500Error.prototype.constructor = Jsonql500Error; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'Jsonql500Error'; + }; + + Object.defineProperties( Jsonql500Error, staticAccessors ); + + return Jsonql500Error; +}(Error)); + +/** + * This is a custom error to throw when pass credential but fail + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { + function JsonqlAuthorisationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlAuthorisationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlAuthorisationError); + } + } + + if ( Error ) JsonqlAuthorisationError.__proto__ = Error; + JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); + JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlAuthorisationError'; + }; + + Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); + + return JsonqlAuthorisationError; +}(Error)); + +/** + * This is a custom error when not supply the credential and try to get contract + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var JsonqlContractAuthError = /*@__PURE__*/(function (Error) { + function JsonqlContractAuthError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlContractAuthError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlContractAuthError); + } + } + + if ( Error ) JsonqlContractAuthError.__proto__ = Error; + JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); + JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 401; + }; + + staticAccessors.name.get = function () { + return 'JsonqlContractAuthError'; + }; + + Object.defineProperties( JsonqlContractAuthError, staticAccessors ); + + return JsonqlContractAuthError; +}(Error)); + +/** + * This is a custom error to throw when the resolver throw error and capture inside the middleware + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var JsonqlResolverAppError = /*@__PURE__*/(function (Error) { + function JsonqlResolverAppError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlResolverAppError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverAppError); + } + } + + if ( Error ) JsonqlResolverAppError.__proto__ = Error; + JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 500; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverAppError'; + }; + + Object.defineProperties( JsonqlResolverAppError, staticAccessors ); + + return JsonqlResolverAppError; +}(Error)); + +/** + * This is a custom error to throw when could not find the resolver + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { + function JsonqlResolverNotFoundError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlResolverNotFoundError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlResolverNotFoundError); + } + } + + if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; + JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); + JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; + + var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; + + staticAccessors.statusCode.get = function () { + return 404; + }; + + staticAccessors.name.get = function () { + return 'JsonqlResolverNotFoundError'; + }; + + Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); + + return JsonqlResolverNotFoundError; +}(Error)); + +// this get throw from within the checkOptions when run through the enum failed +var JsonqlEnumError = /*@__PURE__*/(function (Error) { + function JsonqlEnumError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlEnumError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlEnumError); + } + } + + if ( Error ) JsonqlEnumError.__proto__ = Error; + JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); + JsonqlEnumError.prototype.constructor = JsonqlEnumError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlEnumError'; + }; + + Object.defineProperties( JsonqlEnumError, staticAccessors ); + + return JsonqlEnumError; +}(Error)); + +// this will throw from inside the checkOptions +var JsonqlTypeError = /*@__PURE__*/(function (Error) { + function JsonqlTypeError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlTypeError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlTypeError); + } + } + + if ( Error ) JsonqlTypeError.__proto__ = Error; + JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); + JsonqlTypeError.prototype.constructor = JsonqlTypeError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlTypeError'; + }; + + Object.defineProperties( JsonqlTypeError, staticAccessors ); + + return JsonqlTypeError; +}(Error)); + +// allow supply a custom checker function +// if that failed then we throw this error +var JsonqlCheckerError = /*@__PURE__*/(function (Error) { + function JsonqlCheckerError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlCheckerError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlCheckerError); + } + } + + if ( Error ) JsonqlCheckerError.__proto__ = Error; + JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); + JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlCheckerError'; + }; + + Object.defineProperties( JsonqlCheckerError, staticAccessors ); + + return JsonqlCheckerError; +}(Error)); + +// custom validation error class +// when validaton failed +var JsonqlValidationError = /*@__PURE__*/(function (Error) { + function JsonqlValidationError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlValidationError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlValidationError); + } + } + + if ( Error ) JsonqlValidationError.__proto__ = Error; + JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); + JsonqlValidationError.prototype.constructor = JsonqlValidationError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlValidationError'; + }; + + Object.defineProperties( JsonqlValidationError, staticAccessors ); + + return JsonqlValidationError; +}(Error)); + +// the core stuff to id if it's calling with jsonql +var DATA_KEY = 'data'; +var ERROR_KEY = 'error'; + +var JSONQL_PATH = 'jsonql'; +var DEFAULT_TYPE = 'any'; + +// @TODO remove this is not in use +// export const CLIENT_CONFIG_FILE = '.clients.json'; +// export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; +// type of resolvers +var QUERY_NAME = 'query'; +var MUTATION_NAME = 'mutation'; +var SOCKET_NAME = 'socket'; +var QUERY_ARG_NAME = 'args'; +// for contract-cli +var KEY_WORD = 'continue'; + +var TYPE_KEY = 'type'; +var OPTIONAL_KEY = 'optional'; +var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word +var ARGS_KEY = 'args'; +var CHECKER_KEY = 'checker'; +var ALIAS_KEY = 'alias'; +var LOGIN_NAME = 'login'; +var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later +var LOGOUT_NAME = 'logout'; + +var OR_SEPERATOR = '|'; + +var STRING_TYPE = 'string'; +var BOOLEAN_TYPE = 'boolean'; +var ARRAY_TYPE = 'array'; +var OBJECT_TYPE = 'object'; + +var NUMBER_TYPE = 'number'; +var ARRAY_TYPE_LFT = 'array.<'; +var ARRAY_TYPE_RGT = '>'; + +var NO_ERROR_MSG = 'No message'; +var NO_STATUS_CODE = -1; +var LOGIN_EVENT_NAME = '__login__'; +var LOGOUT_EVENT_NAME = '__logout__'; + +// for ws servers +var WS_REPLY_TYPE = '__reply__'; +var WS_EVT_NAME = '__event__'; +var WS_DATA_NAME = '__data__'; +var EMIT_REPLY_TYPE = 'emit'; +var ACKNOWLEDGE_REPLY_TYPE = 'acknowledge'; +var ERROR_TYPE = 'error'; + +var JS_WS_SOCKET_IO_NAME = 'socket.io'; +var JS_WS_NAME = 'ws'; + +// for ws client +var MESSAGE_PROP_NAME = 'onMessage'; +var RESULT_PROP_NAME = 'onResult'; +var ERROR_PROP_NAME = 'onError'; +var READY_PROP_NAME = 'onReady'; +var SEND_MSG_PROP_NAME = 'send'; +var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; +var HSA_ALGO = 'HS256'; + +/** + * This is a custom error to throw whenever a error happen inside the jsonql + * This help us to capture the right error, due to the call happens in sequence + * @param {string} message to tell what happen + * @param {mixed} extra things we want to add, 500? + */ +var JsonqlError = /*@__PURE__*/(function (Error) { + function JsonqlError() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + Error.apply(this, args); + + this.message = args[0]; + this.detail = args[1]; + + this.className = JsonqlError.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, JsonqlError); + } + } + + if ( Error ) JsonqlError.__proto__ = Error; + JsonqlError.prototype = Object.create( Error && Error.prototype ); + JsonqlError.prototype.constructor = JsonqlError; + + var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlError'; + }; + + staticAccessors.statusCode.get = function () { + return NO_STATUS_CODE; + }; + + Object.defineProperties( JsonqlError, staticAccessors ); + + return JsonqlError; +}(Error)); + +// this is from an example from Koa team to use for internal middleware ctx.throw +// but after the test the res.body part is unable to extract the required data +// I keep this one here for future reference + +var JsonqlServerError = /*@__PURE__*/(function (Error) { + function JsonqlServerError(statusCode, message) { + Error.call(this, message); + this.statusCode = statusCode; + this.className = JsonqlServerError.name; + } + + if ( Error ) JsonqlServerError.__proto__ = Error; + JsonqlServerError.prototype = Object.create( Error && Error.prototype ); + JsonqlServerError.prototype.constructor = JsonqlServerError; + + var staticAccessors = { name: { configurable: true } }; + + staticAccessors.name.get = function () { + return 'JsonqlServerError'; + }; + + Object.defineProperties( JsonqlServerError, staticAccessors ); + + return JsonqlServerError; +}(Error)); + +/** + * this will put into generator call at the very end and catch + * the error throw from inside then throw again + * this is necessary because we split calls inside and the throw + * will not reach the actual client unless we do it this way + * @param {object} e Error + * @return {void} just throw + */ +function finalCatch(e) { + // this is a hack to get around the validateAsync not actually throw error + // instead it just rejected it with the array of failed parameters + if (Array.isArray(e)) { + // if we want the message then I will have to create yet another function + // to wrap this function to provide the name prop + throw new JsonqlValidationError('', e); + } + var msg = e.message || NO_ERROR_MSG; + var detail = e.detail || e; + switch (true) { + case e instanceof Jsonql406Error: + throw new Jsonql406Error(msg, detail); + case e instanceof Jsonql500Error: + throw new Jsonql500Error(msg, detail); + case e instanceof JsonqlAuthorisationError: + throw new JsonqlAuthorisationError(msg, detail); + case e instanceof JsonqlContractAuthError: + throw new JsonqlContractAuthError(msg, detail); + case e instanceof JsonqlResolverAppError: + throw new JsonqlResolverAppError(msg, detail); + case e instanceof JsonqlResolverNotFoundError: + throw new JsonqlResolverNotFoundError(msg, detail); + case e instanceof JsonqlEnumError: + throw new JsonqlEnumError(msg, detail); + case e instanceof JsonqlTypeError: + throw new JsonqlTypeError(msg, detail); + case e instanceof JsonqlCheckerError: + throw new JsonqlCheckerError(msg, detail); + case e instanceof JsonqlValidationError: + throw new JsonqlValidationError(msg, detail); + case e instanceof JsonqlServerError: + throw new JsonqlServerError(msg, detail); + default: + throw new JsonqlError(msg, detail); + } +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Built-in value references. */ +var Symbol = root.Symbol; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString$1 = objectProto$1.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString$1.call(value); +} + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag$1 && symToStringTag$1 in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** Used for built-in method references. */ +var funcProto = Function.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var funcProto$1 = Function.prototype, + objectProto$2 = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$1 = funcProto$1.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/* Built-in method references that are verified to be native. */ +var WeakMap$1 = getNative(root, 'WeakMap'); + +/** Built-in value references. */ +var objectCreate = Object.create; + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** Used for built-in method references. */ +var objectProto$3 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$2.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$1 = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; +} + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +/** Used for built-in method references. */ +var objectProto$4 = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4; + + return value === proto; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +/** Used for built-in method references. */ +var objectProto$5 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$3 = objectProto$5.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$3.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** `Object#toString` result references. */ +var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag$1 = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** Detect free variable `exports`. */ +var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports$1 && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** Used for built-in method references. */ +var objectProto$6 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$4 = objectProto$6.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$4.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +/** Used for built-in method references. */ +var objectProto$7 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$5 = objectProto$7.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$5.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +/** Used for built-in method references. */ +var objectProto$8 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$6 = objectProto$8.hasOwnProperty; + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$6.call(object, key)))) { + result.push(key); + } + } + return result; +} + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto$9 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$7.call(data, key) ? data[key] : undefined; +} + +/** Used for built-in method references. */ +var objectProto$a = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$8 = objectProto$a.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$8.call(data, key); +} + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; +} + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/* Built-in method references that are verified to be native. */ +var Map$1 = getNative(root, 'Map'); + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$1 || ListCache), + 'string': new Hash + }; +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; +} + +// Expose `MapCache`. +memoize.Cache = MapCache; + +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; + +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; +} + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); +} + +/** Used as references for various `Number` constants. */ +var INFINITY$1 = 1 / 0; + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; +} + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +/** `Object#toString` result references. */ +var objectTag$1 = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto$2 = Function.prototype, + objectProto$b = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$2 = funcProto$2.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$9 = objectProto$b.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString$2.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag$1) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$9.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString$2.call(Ctor) == objectCtorString; +} + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$1 = '\\ud800-\\udfff', + rsComboMarksRange$1 = '\\u0300-\\u036f', + reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', + rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, + rsVarRange$1 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange$1 + ']', + rsCombo = '[' + rsComboRange$1 + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange$1 + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ$1 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange$1 + ']?', + rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** Detect free variable `exports`. */ +var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + +/** Built-in value references. */ +var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, + allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; +} + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +/** Used for built-in method references. */ +var objectProto$c = Object.prototype; + +/** Built-in value references. */ +var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); +}; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; +}; + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +/** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); +} + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'); + +/* Built-in method references that are verified to be native. */ +var Promise$1 = getNative(root, 'Promise'); + +/* Built-in method references that are verified to be native. */ +var Set$1 = getNative(root, 'Set'); + +/** `Object#toString` result references. */ +var mapTag$1 = '[object Map]', + objectTag$2 = '[object Object]', + promiseTag = '[object Promise]', + setTag$1 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + +var dataViewTag$1 = '[object DataView]'; + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$1), + weakMapCtorString = toSource(WeakMap$1); + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) || + (Map$1 && getTag(new Map$1) != mapTag$1) || + (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || + (Set$1 && getTag(new Set$1) != setTag$1) || + (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag$2 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$1; + case mapCtorString: return mapTag$1; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$1; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; +} + +var getTag$1 = getTag; + +/** Built-in value references. */ +var Uint8Array = root.Uint8Array; + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; +} + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + +/** `Object#toString` result references. */ +var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$2 = '[object Map]', + numberTag$1 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$2 = '[object Set]', + stringTag$1 = '[object String]', + symbolTag$1 = '[object Symbol]'; + +var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$2 = '[object DataView]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$1 = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$2: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$1: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$1: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$2: + var convert = mapToArray; + + case setTag$2: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$2 = 1; + +/** Used for built-in method references. */ +var objectProto$d = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$a = objectProto$d.hasOwnProperty; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$3 = 1; + +/** `Object#toString` result references. */ +var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$3 = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto$e = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$b = objectProto$e.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag$1 : getTag$1(object), + othTag = othIsArr ? arrayTag$1 : getTag$1(other); + + objTag = objTag == argsTag$2 ? objectTag$3 : objTag; + othTag = othTag == argsTag$2 ? objectTag$3 : othTag; + + var objIsObj = objTag == objectTag$3, + othIsObj = othTag == objectTag$3, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$b.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; +} + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); +} + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; +} + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ +function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); +} + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Gets the value at `key`, unless `key` is "__proto__". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function safeGet(object, key) { + if (key == '__proto__') { + return; + } + + return object[key]; +} + +/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ +function toPlainObject(value) { + return copyObject(value, keysIn(value)); +} + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); +} + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +/** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ +function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; +} + +/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ +function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwn); +} + +/** `Object#toString` result references. */ +var stringTag$2 = '[object String]'; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag$2); +} + +/** `Object#toString` result references. */ +var boolTag$2 = '[object Boolean]'; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag$2); +} + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} + +/** `Object#toString` result references. */ +var numberTag$2 = '[object Number]'; + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag$2); +} + +/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ +function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; +} + +/** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ +function isNull(value) { + return value === null; +} + +/** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ +function isUndefined(value) { + return value === undefined; +} + +/** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ +function mapKeys(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; +} + +/** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ +function mapValues(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; +} + +/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ +var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); +}); + +/** Error message constants. */ +var FUNC_ERROR_TEXT$1 = 'Expected a function'; + +/** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ +function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$1); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; +} + +/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; +} + +/** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ +function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; +} + +/** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ +function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = baseIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); +} + +/** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ +function omitBy(object, predicate) { + return pickBy(object, negate(baseIteratee(predicate))); +} + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ +function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +/** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ +function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** + * Removes leading and trailing whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ +function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + chrSymbols = stringToArray(chars), + start = charsStartIndex(strSymbols, chrSymbols), + end = charsEndIndex(strSymbols, chrSymbols) + 1; + + return castSlice(strSymbols, start, end).join(''); +} + +/** + * Check several parameter that there is something in the param + * @param {*} param input + * @return {boolean} + */ + +function notEmpty (a) { + if (isArray(a)) { + return true; + } + return a !== undefined && a !== null && trim(a) !== ''; +} + +// validator numbers +/** + * @2015-05-04 found a problem if the value is a number like string + * it will pass, so add a check if it's string before we pass to next + * @param {number} value expected value + * @return {boolean} true if OK + */ +var checkIsNumber = function(value) { + return isString(value) ? false : !isNaN( parseFloat(value) ) +}; + +// validate string type +/** + * @param {string} value expected value + * @return {boolean} true if OK + */ +var checkIsString = function(value) { + return (trim(value) !== '') ? isString(value) : false; +}; + +// check for boolean +/** + * @param {boolean} value expected + * @return {boolean} true if OK + */ +var checkIsBoolean = function(value) { + return isBoolean(value); +}; + +// validate any thing only check if there is something +/** + * @param {*} value the value + * @param {boolean} [checkNull=true] strict check if there is null value + * @return {boolean} true is OK + */ +var checkIsAny = function(value, checkNull) { + if ( checkNull === void 0 ) checkNull = true; + + if (!isUndefined(value) && value !== '' && trim(value) !== '') { + if (checkNull === false || (checkNull === true && !isNull(value))) { + return true; + } + } + return false; +}; + +// Good practice rule - No magic number + +var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; +var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; +var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; +// @TODO the jsdoc return array. and we should also allow array syntax +var DEFAULT_TYPE$1 = DEFAULT_TYPE; +var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; +var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; + +var TYPE_KEY$1 = TYPE_KEY; +var OPTIONAL_KEY$1 = OPTIONAL_KEY; +var ENUM_KEY$1 = ENUM_KEY; +var ARGS_KEY$1 = ARGS_KEY; +var CHECKER_KEY$1 = CHECKER_KEY; +var ALIAS_KEY$1 = ALIAS_KEY; + +var ARRAY_TYPE$1 = ARRAY_TYPE; +var OBJECT_TYPE$1 = OBJECT_TYPE; +var STRING_TYPE$1 = STRING_TYPE; +var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; +var NUMBER_TYPE$1 = NUMBER_TYPE; +var KEY_WORD$1 = KEY_WORD; +var OR_SEPERATOR$1 = OR_SEPERATOR; + +// not actually in use +// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; + +// primitive types + +/** + * this is a wrapper method to call different one based on their type + * @param {string} type to check + * @return {function} a function to handle the type + */ +var combineFn = function(type) { + switch (type) { + case NUMBER_TYPE$1: + return checkIsNumber; + case STRING_TYPE$1: + return checkIsString; + case BOOLEAN_TYPE$1: + return checkIsBoolean; + default: + return checkIsAny; + } +}; + +// validate array type + +/** + * @param {array} value expected + * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well + * @return {boolean} true if OK + */ +var checkIsArray = function(value, type) { + if ( type === void 0 ) type=''; + + if (isArray(value)) { + if (type === '' || trim(type)==='') { + return true; + } + // we test it in reverse + // @TODO if the type is an array (OR) then what? + // we need to take into account this could be an array + var c = value.filter(function (v) { return !combineFn(type)(v); }); + return !(c.length > 0) + } + return false; +}; + +/** + * check if it matches the array. pattern + * @param {string} type + * @return {boolean|array} false means NO, always return array + */ +var isArrayLike$1 = function(type) { + // @TODO could that have something like array<> instead of array.<>? missing the dot? + // because type script is Array without the dot + if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { + var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); + if (_type.indexOf(OR_SEPERATOR$1)) { + return _type.split(OR_SEPERATOR$1) + } + return [_type] + } + return false; +}; + +/** + * we might encounter something like array. then we need to take it apart + * @param {object} p the prepared object for processing + * @param {string|array} type the type came from + * @return {boolean} for the filter to operate on + */ +var arrayTypeHandler = function(p, type) { + var arg = p.arg; + // need a special case to handle the OR type + // we need to test the args instead of the type(s) + if (type.length > 1) { + return !arg.filter(function (v) { return ( + !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) + ); }).length; + } + // type is array so this will be or! + return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; +}; + +// validate object type +/** + * @TODO if provide with the keys then we need to check if the key:value type as well + * @param {object} value expected + * @param {array} [keys=null] if it has the keys array to compare as well + * @return {boolean} true if OK + */ +var checkIsObject = function(value, keys) { + if ( keys === void 0 ) keys=null; + + if (isPlainObject(value)) { + if (!keys) { + return true; + } + if (checkIsArray(keys)) { + // please note we DON'T care if some is optional + // plese refer to the contract.json for the keys + return !keys.filter(function (key) { + var _value = value[key.name]; + return !(key.type.length > key.type.filter(function (type) { + var tmp; + if (!isUndefined(_value)) { + if ((tmp = isArrayLike$1(type)) !== false) { + return !arrayTypeHandler({arg: _value}, tmp) + // return tmp.filter(t => !checkIsArray(_value, t)).length; + // @TODO there might be an object within an object with keys as well :S + } + return !combineFn(type)(_value) + } + return true; + }).length) + }).length; + } + } + return false; +}; + +/** + * fold this into it's own function to handler different object type + * @param {object} p the prepared object for process + * @return {boolean} + */ +var objectTypeHandler = function(p) { + var arg = p.arg; + var param = p.param; + var _args = [arg]; + if (Array.isArray(param.keys) && param.keys.length) { + _args.push(param.keys); + } + // just simple check + return checkIsObject.apply(null, _args) +}; + +// move the index.js code here that make more sense to find where things are + +// import debug from 'debug' +// const debugFn = debug('jsonql-params-validator:validator') +// also export this for use in other places + +/** + * We need to handle those optional parameter without a default value + * @param {object} params from contract.json + * @return {boolean} for filter operation false is actually OK + */ +var optionalHandler = function( params ) { + var arg = params.arg; + var param = params.param; + if (notEmpty(arg)) { + // debug('call optional handler', arg, params); + // loop through the type in param + return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } + ).length) + } + return false; +}; + +/** + * actually picking the validator + * @param {*} type for checking + * @param {*} value for checking + * @return {boolean} true on OK + */ +var validateHandler = function(type, value) { + var tmp; + switch (true) { + case type === OBJECT_TYPE$1: + // debugFn('call OBJECT_TYPE') + return !objectTypeHandler(value) + case type === ARRAY_TYPE$1: + // debugFn('call ARRAY_TYPE') + return !checkIsArray(value.arg) + // @TODO when the type is not present, it always fall through here + // so we need to find a way to actually pre-check the type first + // AKA check the contract.json map before running here + case (tmp = isArrayLike$1(type)) !== false: + // debugFn('call ARRAY_LIKE: %O', value) + return !arrayTypeHandler(value, tmp) + default: + return !combineFn(type)(value.arg) + } +}; + +/** + * it get too longer to fit in one line so break it out from the fn below + * @param {*} arg value + * @param {object} param config + * @return {*} value or apply default value + */ +var getOptionalValue = function(arg, param) { + if (!isUndefined(arg)) { + return arg; + } + return (param.optional === true && !isUndefined(param.defaultvalue) ? param.defaultvalue : null) +}; + +/** + * padding the arguments with defaultValue if the arguments did not provide the value + * this will be the name export + * @param {array} args normalized arguments + * @param {array} params from contract.json + * @return {array} merge the two together + */ +var normalizeArgs = function(args, params) { + // first we should check if this call require a validation at all + // there will be situation where the function doesn't need args and params + if (!checkIsArray(params)) { + // debugFn('params value', params) + throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) + } + if (params.length === 0) { + return []; + } + if (!checkIsArray(args)) { + throw new JsonqlError(ARGS_NOT_ARRAY_ERR) + } + // debugFn(args, params); + // fall through switch + switch(true) { + case args.length == params.length: // standard + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] + } + ); }); + case params[0].variable === true: // using spread syntax + var type = params[0].type; + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, // keep the index for reference + param: params[i] || { type: type, name: '_' } + } + ); }); + // with optional defaultValue parameters + case args.length < params.length: + return params.map(function (param, i) { return ( + { + param: param, + index: i, + arg: getOptionalValue(args[i], param), + optional: param.optional || false + } + ); }); + // this one pass more than it should have anything after the args.length will be cast as any type + case args.length > params.length && params.length === 1: + // this happens when we have those array. type + var tmp, _type = [ DEFAULT_TYPE$1 ]; + // we only looking at the first one, this might be a @BUG! + if ((tmp = isArrayLike$1(params[0].type[0])) !== false) { + _type = tmp; + } + // if not then we fall back to the following + return args.map(function (arg, i) { return ( + { + arg: arg, + index: i, + param: params[i] || { type: _type, name: '_' } + } + ); }); + // @TODO find out if there is more cases not cover + default: // this should never happen + // debugFn('args', args) + // debugFn('params', params) + // this is unknown therefore we just throw it! + throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) + } +}; + +// what we want is after the validaton we also get the normalized result +// which is with the optional property if the argument didn't provide it +/** + * process the array of params back to their arguments + * @param {array} result the params result + * @return {array} arguments + */ +var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; + +/** + * validator main interface + * @param {array} args the arguments pass to the method call + * @param {array} params from the contract for that method + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {array} empty array on success, or failed parameter and reasons + */ +var validateSync = function(args, params, withResult) { + var obj; + + if ( withResult === void 0 ) withResult = false; + var cleanArgs = normalizeArgs(args, params); + var checkResult = cleanArgs.filter(function (p) { + if (p.param.optional === true) { + return optionalHandler(p) + } + // because array of types means OR so if one pass means pass + return !(p.param.type.length > p.param.type.filter( + function (type) { return validateHandler(type, p); } + ).length) + }); + // using the same convention we been using all this time + return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) +}; + +/** + * A wrapper method that return promise + * @param {array} args arguments + * @param {array} params from contract.json + * @param {boolean} [withResul=false] if true then this will return the normalize result as well + * @return {object} promise.then or catch + */ +var validateAsync = function(args, params, withResult) { + if ( withResult === void 0 ) withResult = false; + + return new Promise(function (resolver, rejecter) { + var result = validateSync(args, params, withResult); + if (withResult) { + return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) + : resolver(result[DATA_KEY]) + } + // the different is just in the then or catch phrase + return result.length ? rejecter(result) : resolver([]) + }) +}; + +/** + * @param {array} arr Array for check + * @param {*} value target + * @return {boolean} true on successs + */ +var isInArray = function(arr, value) { + return !!arr.filter(function (a) { return a === value; }).length; +}; + +/** + * @param {object} obj for search + * @param {string} key target + * @return {boolean} true on success + */ +var checkKeyInObject = function(obj, key) { + var keys = Object.keys(obj); + return isInArray(keys, key) +}; + +// import debug from 'debug'; +// const debugFn = debug('jsonql-params-validator:options:prepare') + +// just not to make my head hurt +var isEmpty = function (value) { return !notEmpty(value); }; + +/** + * Map the alias to their key then grab their value over + * @param {object} config the user supplied config + * @param {object} appProps the default option map + * @return {object} the config keys replaced with the appProps key by the ALIAS + */ +function mapAliasConfigKeys(config, appProps) { + // need to do two steps + // 1. take key with alias key + var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); + if (isEqual(aliasMap, {})) { + return config; + } + return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) +} + +/** + * We only want to run the valdiation against the config (user supplied) value + * but keep the defaultOptions untouch + * @param {object} config configuraton supplied by user + * @param {object} appProps the default options map + * @return {object} the pristine values that will add back to the final output + */ +function preservePristineValues(config, appProps) { + // @BUG this will filter out those that is alias key + // we need to first map the alias keys back to their full key + var _config = mapAliasConfigKeys(config, appProps); + // take the default value out + var pristineValues = mapValues( + omitBy(appProps, function (value, key) { return checkKeyInObject(_config, key); }), + function (value) { return value.args; } + ); + // for testing the value + var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !checkKeyInObject(_config, key); }); + // output + return { + pristineValues: pristineValues, + checkAgainstAppProps: checkAgainstAppProps, + config: _config // passing this correct values back + } +} + +/** + * This will take the value that is ONLY need to check + * @param {object} config that one + * @param {object} props map for creating checking + * @return {object} put that arg into the args + */ +function processConfigAction(config, props) { + // debugFn('processConfigAction', props) + // v.1.2.0 add checking if its mark optional and the value is empty then pass + return mapValues(props, function (value, key) { + var obj, obj$1; + + return ( + isUndefined(config[key]) || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) + ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) + : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) + ); + } + ) +} + +/** + * Quick transform + * @TODO we should only validate those that is pass from the config + * and pass through those values that is from the defaultOptions + * @param {object} opts that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ +function prepareArgsForValidation(opts, appProps) { + var ref = preservePristineValues(opts, appProps); + var config = ref.config; + var pristineValues = ref.pristineValues; + var checkAgainstAppProps = ref.checkAgainstAppProps; + // output + return [ + processConfigAction(config, checkAgainstAppProps), + pristineValues + ] +} + +// breaking the whole thing up to see what cause the multiple calls issue + +// import debug from 'debug'; +// const debugFn = debug('jsonql-params-validator:options:validation') + +/** + * just make sure it returns an array to use + * @param {*} arg input + * @return {array} output + */ +var toArray = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; + +/** + * DIY in array + * @param {array} arr to check against + * @param {*} value to check + * @return {boolean} true on OK + */ +var inArray = function (arr, value) { return ( + !!arr.filter(function (v) { return v === value; }).length +); }; + +/** + * break out to make the code easier to read + * @param {object} value to process + * @param {function} cb the validateSync + * @return {array} empty on success + */ +function validateHandler$1(value, cb) { + var obj; + + // cb is the validateSync methods + var args = [ + [ value[ARGS_KEY$1] ], + [( obj = {}, obj[TYPE_KEY$1] = toArray(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] + ]; + // debugFn('validateHandler', args) + return Reflect.apply(cb, null, args) +} + +/** + * Check against the enum value if it's provided + * @param {*} value to check + * @param {*} enumv to check against if it's not false + * @return {boolean} true on OK + */ +var enumHandler = function (value, enumv) { + if (checkIsArray(enumv)) { + return inArray(enumv, value) + } + return true; +}; + +/** + * Allow passing a function to check the value + * There might be a problem here if the function is incorrect + * and that will makes it hard to debug what is going on inside + * @TODO there could be a few feature add to this one under different circumstance + * @param {*} value to check + * @param {function} checker for checking + */ +var checkerHandler = function (value, checker) { + try { + return isFunction(checker) ? checker.apply(null, [value]) : false; + } catch (e) { + return false; + } +}; + +/** + * Taken out from the runValidaton this only validate the required values + * @param {array} args from the config2argsAction + * @param {function} cb validateSync + * @return {array} of configuration values + */ +function runValidationAction(cb) { + return function (value, key) { + // debugFn('runValidationAction', key, value) + if (value[KEY_WORD$1]) { + return value[ARGS_KEY$1] + } + var check = validateHandler$1(value, cb); + if (check.length) { + // debugFn('runValidationAction', key, value) + throw new JsonqlTypeError(key, check) + } + if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { + throw new JsonqlEnumError(key) + } + if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { + throw new JsonqlCheckerError(key) + } + return value[ARGS_KEY$1] + } +} + +/** + * @param {object} args from the config2argsAction + * @param {function} cb validateSync + * @return {object} of configuration values + */ +function runValidation(args, cb) { + var argsForValidate = args[0]; + var pristineValues = args[1]; + // turn the thing into an array and see what happen here + // debugFn('_args', argsForValidate) + var result = mapValues(argsForValidate, runValidationAction(cb)); + return merge(result, pristineValues) +} + +// this is port back from the client to share across all projects + +// import debug from 'debug' +// const debugFn = debug('jsonql-params-validator:check-options-async') + +/** + * Quick transform + * @param {object} config that one + * @param {object} appProps mutation configuration options + * @return {object} put that arg into the args + */ +var configToArgs = function (config, appProps) { + return Promise.resolve( + prepareArgsForValidation(config, appProps) + ) +}; + +/** + * @param {object} config user provide configuration option + * @param {object} appProps mutation configuration options + * @param {object} constProps the immutable configuration options + * @param {function} cb the validateSync method + * @return {object} Promise resolve merge config object + */ +function checkOptionsAsync(config, appProps, constProps, cb) { + if ( config === void 0 ) config = {}; + + return configToArgs(config, appProps) + .then(function (args1) { + // debugFn('args', args1) + return runValidation(args1, cb) + }) + // next if every thing good then pass to final merging + .then(function (args2) { return merge({}, args2, constProps); }) +} + +// create function to construct the config entry so we don't need to keep building object +// import debug from 'debug'; +// const debugFn = debug('jsonql-params-validator:construct-config'); +/** + * @param {*} args value + * @param {string} type for value + * @param {boolean} [optional=false] + * @param {boolean|array} [enumv=false] + * @param {boolean|function} [checker=false] + * @return {object} config entry + */ +function constructConfigFn(args, type, optional, enumv, checker, alias) { + if ( optional === void 0 ) optional=false; + if ( enumv === void 0 ) enumv=false; + if ( checker === void 0 ) checker=false; + if ( alias === void 0 ) alias=false; + + var base = {}; + base[ARGS_KEY] = args; + base[TYPE_KEY] = type; + if (optional === true) { + base[OPTIONAL_KEY] = true; + } + if (checkIsArray(enumv)) { + base[ENUM_KEY] = enumv; + } + if (isFunction(checker)) { + base[CHECKER_KEY] = checker; + } + if (isString(alias)) { + base[ALIAS_KEY] = alias; + } + return base; +} + +// export also create wrapper methods + +// import debug from 'debug'; +// const debugFn = debug('jsonql-params-validator:options:index'); + +/** + * This has a different interface + * @param {*} value to supply + * @param {string|array} type for checking + * @param {object} params to map against the config check + * @param {array} params.enumv NOT enum + * @param {boolean} params.optional false then nothing + * @param {function} params.checker need more work on this one later + * @param {string} params.alias mostly for cmd + */ +var createConfig = function (value, type, params) { + if ( params === void 0 ) params = {}; + + // Note the enumv not ENUM + // const { enumv, optional, checker, alias } = params; + // let args = [value, type, optional, enumv, checker, alias]; + var o = params[OPTIONAL_KEY]; + var e = params[ENUM_KEY]; + var c = params[CHECKER_KEY]; + var a = params[ALIAS_KEY]; + return constructConfigFn.apply(null, [value, type, o, e, c, a]) +}; + +/** + * We recreate the method here to avoid the circlar import + * @param {object} config user supply configuration + * @param {object} appProps mutation options + * @param {object} [constantProps={}] optional: immutation options + * @return {object} all checked configuration + */ +var checkConfigAsync = function(validateSync) { + return function(config, appProps, constantProps) { + if ( constantProps === void 0 ) constantProps= {}; + + return checkOptionsAsync(config, appProps, constantProps, validateSync) + } +}; + +// since this need to use everywhere might as well include in the validator + +function checkIsContract(contract) { + return checkIsObject(contract) + && ( + checkKeyInObject(contract, QUERY_NAME) + || checkKeyInObject(contract, MUTATION_NAME) + || checkKeyInObject(contract, SOCKET_NAME) + ) +} + +// craete several helper function to construct / extract the payload + +/** + * Get name from the payload (ported back from jsonql-koa) + * @param {*} payload to extract from + * @return {string} name + */ +function getNameFromPayload(payload) { + return Object.keys(payload)[0] +} + +/** + * @param {string} resolverName name of function + * @param {array} [args=[]] from the ...args + * @return {object} formatted argument + */ +function createQuery(resolverName, args) { + var obj, obj$1; + + if ( args === void 0 ) args = []; + if (checkIsString(resolverName) && checkIsArray(args)) { + return ( obj$1 = {}, obj$1[resolverName] = ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ), obj$1 ) + } + throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) +} + +// string version of the above +function createQueryStr(resolverName, args) { + return JSON.stringify(createQuery(resolverName, args)) +} + +// export +var isString$1 = checkIsString; +var isArray$1 = checkIsArray; +var validateSync$1 = validateSync; +var validateAsync$1 = validateAsync; + +var createConfig$1 = createConfig; + +var checkConfigAsync$1 = checkConfigAsync(validateSync); + +var isKeyInObject = checkKeyInObject; + +var isContract = checkIsContract; +var createQueryStr$1 = createQueryStr; +var getNameFromPayload$1 = getNameFromPayload; + +/** + * Try to normalize it to use between browser and node + * @param {string} name for the debug output + * @return {function} debug + */ +var getDebug = function (name) { + if (debug$2) { + return debug$2('jsonql-ws-client').extend(name) + } + return function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + console.info.apply(null, [name].concat(args)); + } +}; +try { + if (window && window.localStorage) { + localStorage.setItem('DEBUG', 'jsonql-ws-client*'); + } +} catch(e) {} + +// since both the ws and io version are +var debugFn = getDebug('create-nsp-client'); +/** + * wrapper method to create a nsp without login + * @param {string|boolean} namespace namespace url could be false + * @param {object} opts configuration + * @return {object} ws client instance + */ +var nspClient = function (namespace, opts) { + var wssPath = opts.wssPath; + var wsOptions = opts.wsOptions; + var hostname = opts.hostname; + var url = namespace ? [hostname, namespace].join('/') : wssPath; + return opts.nspClient(url, wsOptions) +}; + +/** + * wrapper method to create a nsp with token auth + * @param {string} namespace namespace url + * @param {object} opts configuration + * @return {object} ws client instance + */ +var nspAuthClient = function (namespace, opts) { + var wssPath = opts.wssPath; + var token = opts.token; + var wsOptions = opts.wsOptions; + var hostname = opts.hostname; + var url = namespace ? [hostname, namespace].join('/') : wssPath; + return opts.nspAuthClient(url, token, wsOptions) +}; + +// constants + +var SOCKET_IO = JS_WS_SOCKET_IO_NAME; +var WS = JS_WS_NAME; + +var AVAILABLE_SERVERS = [SOCKET_IO, WS]; + +var SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'; + +var MISSING_PROP_ERR = 'Missing property in contract!'; + +var EMIT_EVT = EMIT_REPLY_TYPE; + +var UNKNOWN_RESULT = 'UKNNOWN RESULT!'; + +var MY_NAMESPACE = 'myNamespace'; + +/** + * Got to make sure the connection order otherwise + * it will hang + * @param {object} nspSet contract + * @param {string} publicNamespace like the name said + * @return {array} namespaces in order + */ +function getNamespaceInOrder(nspSet, publicNamespace) { + var names = []; // need to make sure the order! + for (var namespace in nspSet) { + if (namespace === publicNamespace) { + names[1] = namespace; + } else { + names[0] = namespace; + } + } + return names; +} + +var obj, obj$1; +var debug = getDebug('check-options'); + +var fixWss = function (url, serverType) { + // ws only allow ws:// path + if (serverType===WS) { + return url.replace('http://', 'ws://') + } + return url; +}; + +var getHostName = function () { return ( + [window.location.protocol, window.location.host].join('//') +); }; + +var constProps = { + // this will be the switcher! + nspClient: null, + nspAuthClient: null, + // contructed path + wssPath: '' +}; + +var defaultOptions = { + loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), + // we will use this for determine the socket.io client type as well + useJwt: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE]), + hostname: createConfig$1(false, [STRING_TYPE]), + namespace: createConfig$1(JSONQL_PATH, [STRING_TYPE]), + wsOptions: createConfig$1({transports: ['websocket'], 'force new connection' : true}, [OBJECT_TYPE]), + serverType: createConfig$1(SOCKET_IO, [STRING_TYPE], ( obj = {}, obj[ENUM_KEY] = AVAILABLE_SERVERS, obj )), + // we require the contract already generated and pass here + contract: createConfig$1({}, [OBJECT_TYPE], ( obj$1 = {}, obj$1[CHECKER_KEY] = isContract, obj$1 )), + enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), + token: createConfig$1(false, [STRING_TYPE]) +}; +// export +function checkOptions(config) { + return checkConfigAsync$1(config, defaultOptions, constProps) + .then(function (opts) { + if (!opts.hostname) { + opts.hostname = getHostName(); + } + // @TODO the contract now will supply the namespace information + // and we need to use that to group the namespace call + opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType); + + debug('opts', opts); + return opts; + }) +} + +var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); +var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); + +/** + * generate a 32bit hash based on the function.toString() + * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery + * @param {string} s the converted to string function + * @return {string} the hashed function string + */ +function hashCode(s) { + return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) +} + +// this is the new implementation without the hash key +// export +var EventService = function EventService(config) { + if ( config === void 0 ) config = {}; + + if (config.logger && typeof config.logger === 'function') { + this.logger = config.logger; + } + this.keep = config.keep; + // for the $done setter + this.result = config.keep ? [] : null; + // we need to init the store first otherwise it could be a lot of checking later + this.normalStore = new Map(); + this.lazyStore = new Map(); +}; + +var prototypeAccessors = { $done: { configurable: true },normalStore: { configurable: true },lazyStore: { configurable: true } }; + +/** + * logger function for overwrite + */ +EventService.prototype.logger = function logger () {}; + +////////////////////////// +// PUBLIC METHODS // +////////////////////////// + +/** + * Register your evt handler, note we don't check the type here, + * we expect you to be sensible and know what you are doing. + * @param {string} evt name of event + * @param {function} callback bind method --> if it's array or not + * @param {object} [context=null] to execute this call in + * @return {number} the size of the store + */ +EventService.prototype.$on = function $on (evt , callback , context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + var type = 'on'; + this.validate(evt, callback); + // first need to check if this evt is in lazy store + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register first then call later + if (lazyStoreContent === false) { + this.logger('$on', (evt + " callback is not in lazy store")); + // @TODO we need to check if there was other listener to this + // event and are they the same type then we could solve that + // register the different type to the same event name + + return this.addToNormalStore(evt, type, callback, context) + } + this.logger('$on', (evt + " found in lazy store")); + // this is when they call $trigger before register this callback + var size = 0; + lazyStoreContent.forEach(function (content) { + var payload = content[0]; + var ctx = content[1]; + var t = content[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.run(callback, payload, context || ctx); + size += this$1.addToNormalStore(evt, type, callback, context || ctx); + }); + return size; +}; + +/** + * once only registered it once, there is no overwrite option here + * @NOTE change in v1.3.0 $once can add multiple listeners + * but once the event fired, it will remove this event (see $only) + * @param {string} evt name + * @param {function} callback to execute + * @param {object} [context=null] the handler execute in + * @return {boolean} result + */ +EventService.prototype.$once = function $once (evt , callback , context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'once'; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (lazyStoreContent === false) { + this.logger('$once', (evt + " not in the lazy store")); + // v1.3.0 $once now allow to add multiple listeners + return this.addToNormalStore(evt, type, callback, context) + } else { + // now this is the tricky bit + // there is a potential bug here that cause by the developer + // if they call $trigger first, the lazy won't know it's a once call + // so if in the middle they register any call with the same evt name + // then this $once call will be fucked - add this to the documentation + this.logger('$once', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } +}; + +/** + * This one event can only bind one callbackback + * @param {string} evt event name + * @param {function} callback event handler + * @param {object} [context=null] the context the event handler execute in + * @return {boolean} true bind for first time, false already existed + */ +EventService.prototype.$only = function $only (evt, callback, context) { + var this$1 = this; + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'only'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("$only", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('$only', (evt + " found data in lazy store to execute")); + var list = Array.from(lazyStoreContent); + // $only allow to trigger this multiple time on the single handler + list.forEach( function (l) { + var payload = l[0]; + var ctx = l[1]; + var t = l[2]; + if (t && t !== type) { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this$1.run(callback, payload, context || ctx); + }); + } + return added; +}; + +/** + * $only + $once this is because I found a very subtile bug when we pass a + * resolver, rejecter - and it never fire because that's OLD adeed in v1.4.0 + * @param {string} evt event name + * @param {function} callback to call later + * @param {object} [context=null] exeucte context + * @return {void} + */ +EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { + if ( context === void 0 ) context = null; + + this.validate(evt, callback); + var type = 'onlyOnce'; + var added = false; + var lazyStoreContent = this.takeFromStore(evt); + // this is normal register before call $trigger + var nStore = this.normalStore; + if (!nStore.has(evt)) { + this.logger("$onlyOnce", (evt + " add to store")); + added = this.addToNormalStore(evt, type, callback, context); + } + if (lazyStoreContent !== false) { + // there are data store in lazy store + this.logger('$onlyOnce', lazyStoreContent); + var list = Array.from(lazyStoreContent); + // should never have more than 1 + var ref = list[0]; + var payload = ref[0]; + var ctx = ref[1]; + var t = ref[2]; + if (t && t !== 'onlyOnce') { + throw new Error(("You are trying to register an event already been taken by other type: " + t)) + } + this.run(callback, payload, context || ctx); + // remove this evt from store + this.$off(evt); + } + return added; +}; + +/** + * This is a shorthand of $off + $on added in V1.5.0 + * @param {string} evt event name + * @param {function} callback to exeucte + * @param {object} [context = null] or pass a string as type + * @param {string} [type=on] what type of method to replace + * @return {} + */ +EventService.prototype.$replace = function $replace (evt, callback, context, type) { + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = 'on'; + + if (this.validateType(type)) { + this.$off(evt); + var method = this['$' + type]; + return Reflect.apply(method, this, [evt, callback, context]) + } + throw new Error((type + " is not supported!")) +}; + +/** + * trigger the event + * @param {string} evt name NOT allow array anymore! + * @param {mixed} [payload = []] pass to fn + * @param {object|string} [context = null] overwrite what stored + * @param {string} [type=false] if pass this then we need to add type to store too + * @return {number} if it has been execute how many times + */ +EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + this.validateEvt(evt); + var found = 0; + // first check the normal store + var nStore = this.normalStore; + this.logger('$trigger', nStore); + if (nStore.has(evt)) { + this.logger('$trigger', evt, 'found'); + var nSet = Array.from(nStore.get(evt)); + var ctn = nSet.length; + var hasOnce = false; + for (var i=0; i < ctn; ++i) { + ++found; + // this.logger('found', found) + var ref = nSet[i]; + var _ = ref[0]; + var callback = ref[1]; + var ctx = ref[2]; + var type$1 = ref[3]; + this.run(callback, payload, context || ctx); + if (type$1 === 'once' || type$1 === 'onlyOnce') { + hasOnce = true; + } + } + if (hasOnce) { + nStore.delete(evt); + } + return found; + } + // now this is not register yet + this.addToLazyStore(evt, payload, context, type); + return found; +}; + +/** + * this is an alias to the $trigger + * @NOTE breaking change in V1.6.0 we swap the parameter around + * @param {string} evt event name + * @param {*} params pass to the callback + * @param {string} type of call + * @param {object} context what context callback execute in + * @return {*} from $trigger + */ +EventService.prototype.$call = function $call (evt, params, type, context) { + if ( type === void 0 ) type = false; + if ( context === void 0 ) context = null; + + var args = [evt, params]; + args.push(context, type); + return Reflect.apply(this.$trigger, this, args) +}; + +/** + * remove the evt from all the stores + * @param {string} evt name + * @return {boolean} true actually delete something + */ +EventService.prototype.$off = function $off (evt) { + this.validateEvt(evt); + var stores = [ this.lazyStore, this.normalStore ]; + var found = false; + stores.forEach(function (store) { + if (store.has(evt)) { + found = true; + store.delete(evt); + } + }); + return found; +}; + +/** + * return all the listener from the event + * @param {string} evtName event name + * @param {boolean} [full=false] if true then return the entire content + * @return {array|boolean} listerner(s) or false when not found + */ +EventService.prototype.$get = function $get (evt, full) { + if ( full === void 0 ) full = false; + + this.validateEvt(evt); + var store = this.normalStore; + if (store.has(evt)) { + return Array + .from(store.get(evt)) + .map( function (l) { + if (full) { + return l; + } + var key = l[0]; + var callback = l[1]; + return callback; + }) + } + return false; +}; + +/** + * store the return result from the run + * @param {*} value whatever return from callback + */ +prototypeAccessors.$done.set = function (value) { + this.logger('set $done', value); + if (this.keep) { + this.result.push(value); + } else { + this.result = value; + } +}; + +/** + * @TODO is there any real use with the keep prop? + * getter for $done + * @return {*} whatever last store result + */ +prototypeAccessors.$done.get = function () { + if (this.keep) { + this.logger(this.result); + return this.result[this.result.length - 1] + } + return this.result; +}; + +///////////////////////////// +// PRIVATE METHODS // +///////////////////////////// + +/** + * validate the event name + * @param {string} evt event name + * @return {boolean} true when OK + */ +EventService.prototype.validateEvt = function validateEvt (evt) { + if (typeof evt === 'string') { + return true; + } + throw new Error("event name must be string type!") +}; + +/** + * Simple quick check on the two main parameters + * @param {string} evt event name + * @param {function} callback function to call + * @return {boolean} true when OK + */ +EventService.prototype.validate = function validate (evt, callback) { + if (this.validateEvt(evt)) { + if (typeof callback === 'function') { + return true; + } + } + throw new Error("callback required to be function type!") +}; + +/** + * Check if this type is correct or not added in V1.5.0 + * @param {string} type for checking + * @return {boolean} true on OK + */ +EventService.prototype.validateType = function validateType (type) { + var types = ['on', 'only', 'once', 'onlyOnce']; + return !!types.filter(function (t) { return type === t; }).length; +}; + +/** + * Run the callback + * @param {function} callback function to execute + * @param {array} payload for callback + * @param {object} ctx context or null + * @return {void} the result store in $done + */ +EventService.prototype.run = function run (callback, payload, ctx) { + this.logger('run', callback, payload, ctx); + this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); +}; + +/** + * Take the content out and remove it from store id by the name + * @param {string} evt event name + * @param {string} [storeName = lazyStore] name of store + * @return {object|boolean} content or false on not found + */ +EventService.prototype.takeFromStore = function takeFromStore (evt, storeName) { + if ( storeName === void 0 ) storeName = 'lazyStore'; + + var store = this[storeName]; // it could be empty at this point + if (store) { + this.logger('takeFromStore', storeName, store); + if (store.has(evt)) { + var content = store.get(evt); + this.logger('takeFromStore', content); + store.delete(evt); + return content; + } + return false; + } + throw new Error((storeName + " is not supported!")) +}; + +/** + * The add to store step is similar so make it generic for resuse + * @param {object} store which store to use + * @param {string} evt event name + * @param {spread} args because the lazy store and normal store store different things + * @return {array} store and the size of the store + */ +EventService.prototype.addToStore = function addToStore (store, evt) { + var args = [], len = arguments.length - 2; + while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; + + var fnSet; + if (store.has(evt)) { + this.logger('addToStore', (evt + " existed")); + fnSet = store.get(evt); + } else { + this.logger('addToStore', ("create new Set for " + evt)); + // this is new + fnSet = new Set(); + } + // lazy only store 2 items - this is not the case in V1.6.0 anymore + // we need to check the first parameter is string or not + if (args.length > 2) { + if (Array.isArray(args[0])) { // lazy store + // check if this type of this event already register in the lazy store + var t = args[2]; + if (!this.checkTypeInLazyStore(evt, t)) { + fnSet.add(args); + } + } else { + if (!this.checkContentExist(args, fnSet)) { + this.logger('addToStore', "insert new", args); + fnSet.add(args); + } + } + } else { // add straight to lazy store + fnSet.add(args); + } + store.set(evt, fnSet); + return [store, fnSet.size] +}; + +/** + * @param {array} args for compare + * @param {object} fnSet A Set to search from + * @return {boolean} true on exist + */ +EventService.prototype.checkContentExist = function checkContentExist (args, fnSet) { + var list = Array.from(fnSet); + return !!list.filter(function (l) { + var hash = l[0]; + if (hash === args[0]) { + return true; + } + return false; + }).length; +}; + +/** + * get the existing type to make sure no mix type add to the same store + * @param {string} evtName event name + * @param {string} type the type to check + * @return {boolean} true you can add, false then you can't add this type + */ +EventService.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { + this.validateEvt(evtName); + this.validateEvt(type); + var all = this.$get(evtName, true); + if (all === false) { + // pristine it means you can add + return true; + } + // it should only have ONE type in ONE event store + return !all.filter(function (list) { + var t = list[3]; + return type !== t; + }).length; +}; + +/** + * This is checking just the lazy store because the structure is different + * therefore we need to use a new method to check it + */ +EventService.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { + this.validateEvt(evtName); + this.validateEvt(type); + var store = this.lazyStore.get(evtName); + this.logger('checkTypeInLazyStore', store); + if (store) { + return !!Array + .from(store) + .filter(function (l) { + var t = l[2]; + return t !== type; + }).length + } + return false; +}; + +/** + * wrapper to re-use the addToStore, + * V1.3.0 add extra check to see if this type can add to this evt + * @param {string} evt event name + * @param {string} type on or once + * @param {function} callback function + * @param {object} context the context the function execute in or null + * @return {number} size of the store + */ +EventService.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { + if ( context === void 0 ) context = null; + + this.logger('addToNormalStore', evt, type, 'add to normal store'); + // @TODO we need to check the existing store for the type first! + if (this.checkTypeInStore(evt, type)) { + this.logger((type + " can add to " + evt + " store")); + var key = this.hashFnToKey(callback); + var args = [this.normalStore, evt, key, callback, context, type]; + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.normalStore = _store; + return size; + } + return false; +}; + +/** + * Add to lazy store this get calls when the callback is not register yet + * so we only get a payload object or even nothing + * @param {string} evt event name + * @param {array} payload of arguments or empty if there is none + * @param {object} [context=null] the context the callback execute in + * @param {string} [type=false] register a type so no other type can add to this evt + * @return {number} size of the store + */ +EventService.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { + if ( payload === void 0 ) payload = []; + if ( context === void 0 ) context = null; + if ( type === void 0 ) type = false; + + // this is add in V1.6.0 + // when there is type then we will need to check if this already added in lazy store + // and no other type can add to this lazy store + var args = [this.lazyStore, evt, this.toArray(payload), context]; + if (type) { + args.push(type); + } + var ref = Reflect.apply(this.addToStore, this, args); + var _store = ref[0]; + var size = ref[1]; + this.lazyStore = _store; + return size; +}; + +/** + * make sure we store the argument correctly + * @param {*} arg could be array + * @return {array} make sured + */ +EventService.prototype.toArray = function toArray (arg) { + return Array.isArray(arg) ? arg : [arg]; +}; + +/** + * setter to store the Set in private + * @param {object} obj a Set + */ +prototypeAccessors.normalStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); +}; + +/** + * @return {object} Set object + */ +prototypeAccessors.normalStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) +}; + +/** + * setter to store the Set in lazy store + * @param {object} obj a Set + */ +prototypeAccessors.lazyStore.set = function (obj) { + NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); +}; + +/** + * @return {object} the lazy store Set + */ +prototypeAccessors.lazyStore.get = function () { + return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) +}; + +/** + * generate a hashKey to identify the function call + * The build-in store some how could store the same values! + * @param {function} fn the converted to string function + * @return {string} hashKey + */ +EventService.prototype.hashFnToKey = function hashFnToKey (fn) { + return hashCode(fn.toString()) + ''; +}; + +Object.defineProperties( EventService.prototype, prototypeAccessors ); + +// default + +// create a clone version so we know which one we actually is using +var JsonqlWsEvt = /*@__PURE__*/(function (NBEventService) { + function JsonqlWsEvt() { + NBEventService.call(this, {logger: getDebug('nb-event-service')}); + } + + if ( NBEventService ) JsonqlWsEvt.__proto__ = NBEventService; + JsonqlWsEvt.prototype = Object.create( NBEventService && NBEventService.prototype ); + JsonqlWsEvt.prototype.constructor = JsonqlWsEvt; + + var prototypeAccessors = { name: { configurable: true } }; + + prototypeAccessors.name.get = function () { + return 'jsonql-ws-client' + }; + + Object.defineProperties( JsonqlWsEvt.prototype, prototypeAccessors ); + + return JsonqlWsEvt; +}(EventService)); + +// This is ported back from ws-server and it will get use in the server / client side + +function extractSocketPart(contract) { + if (isKeyInObject(contract, 'socket')) { + return contract.socket; + } + return contract; +} + +/** + * @BUG we should check the socket part instead of expect the downstream to read the menu! + * We only need this when the enableAuth is true otherwise there is only one namespace + * @param {object} contract the socket part of the contract file + * @return {object} 1. remap the contract using the namespace --> resolvers + * 2. the size of the object (1 all private, 2 mixed public with private) + * 3. which namespace is public + */ +function groupByNamespace(contract) { + var socket = extractSocketPart(contract); + + var nspSet = {}; + var size = 0; + var publicNamespace; + for (var resolverName in socket) { + var params = socket[resolverName]; + var namespace = params.namespace; + if (namespace) { + if (!nspSet[namespace]) { + ++size; + nspSet[namespace] = {}; + } + nspSet[namespace][resolverName] = params; + if (!publicNamespace) { + if (params.public) { + publicNamespace = namespace; + } + } + } + } + return { size: size, nspSet: nspSet, publicNamespace: publicNamespace } +} + +// This is ported back from ws-client +// the idea if from https://decembersoft.com/posts/promises-in-serial-with-array-reduce/ +/** + * previously we already make sure the order of the namespaces + * and attach the auth client to it + * @param {array} promises array of unresolved promises + * @return {object} promise resolved with the array of promises resolved results + */ +function chainPromises(promises) { + return promises.reduce(function (promiseChain, currentTask) { return ( + promiseChain.then(function (chainResults) { return ( + currentTask.then(function (currentResult) { return ( + chainResults.concat( [currentResult]) + ); }) + ); }) + ); }, Promise.resolve([])) +} + +/** + * The code was extracted from: + * https://github.com/davidchambers/Base64.js + */ + +var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function InvalidCharacterError(message) { + this.message = message; +} + +InvalidCharacterError.prototype = new Error(); +InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + +function polyfill (input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = str.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; +} + + +var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; + +function InvalidTokenError(message) { + this.message = message; +} + +InvalidTokenError.prototype = new Error(); +InvalidTokenError.prototype.name = 'InvalidTokenError'; + +var obj$2, obj$1$1, obj$2$1, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; + +var appProps = { + algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), + expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'exp', obj$2[OPTIONAL_KEY] = true, obj$2 )), + notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1$1 = {}, obj$1$1[ALIAS_KEY] = 'nbf', obj$1$1[OPTIONAL_KEY] = true, obj$1$1 )), + audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2$1 = {}, obj$2$1[ALIAS_KEY] = 'iss', obj$2$1[OPTIONAL_KEY] = true, obj$2$1 )), + subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), + issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), + noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), + header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), + keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), + mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) +}; + +// ws client using native WebSocket + +function getWS() { + switch(true) { + case (typeof WebSocket !== 'undefined'): + return WebSocket; + case (typeof MozWebSocket !== 'undefined'): + return MozWebSocket; + // case (typeof global !== 'undefined'): + // return global.WebSocket || global.MozWebSocket; + case (typeof window !== 'undefined'): + return window.WebSocket || window.MozWebSocket; + // case (typeof self !== 'undefined'): + // return self.WebSocket || self.MozWebSocket; + default: + throw new JsonqlValidationError('WebSocket is NOT SUPPORTED!') + } +} + +var WS$1 = getWS(); + +// mapping the resolver to their respective nsp +var debug$1 = getDebug('process-contract'); + +/** + * Just make sure the object contain what we are looking for + * @param {object} opts configuration from checkOptions + * @return {object} the target content + */ +var getResolverList = function (contract) { + if (contract) { + var socket = contract.socket; + if (socket) { + return socket; + } + } + throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR) +}; + +/** + * process the contract first + * @param {object} opts configuration + * @return {object} sorted list + */ +function processContract(opts) { + var obj; + + var contract = opts.contract; + var enableAuth = opts.enableAuth; + if (enableAuth) { + return groupByNamespace(contract) + } + return { + nspSet: ( obj = {}, obj[JSONQL_PATH] = getResolverList(contract), obj ), + publicNamespace: JSONQL_PATH, + size: 1 // this prop is pretty meaningless now + } +} + +// export the util methods + +var toArray$1 = function (arg) { return isArray$1(arg) ? arg : [arg]; }; + +/** + * very simple tool to create the event name + * @param {string} [...args] spread + * @return {string} join by _ + */ +var createEvt = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return args.join('_'); +}; + +/** + * Unbind the event + * @param {object} ee EventEmitter + * @param {string} namespace + * @return {void} + */ +var clearMainEmitEvt = function (ee, namespace) { + var nsps = isArray$1(namespace) ? namespace : [namespace]; + nsps.forEach(function (n) { + ee.$off(createEvt(n, EMIT_EVT)); + }); +}; + +/** + * @param {*} args arguments to send + *@return {object} formatted payload + */ +var formatPayload = function (args) { + var obj; + + return ( + ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) +); +}; + +/** + * @param {object} nsps namespace as key + * @param {string} type of server + */ +var disconnect = function (nsps, type) { + if ( type === void 0 ) type = JS_WS_SOCKET_IO_NAME; + + try { + var method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate'; + for (var namespace in nsps) { + var nsp = nsps[namespace]; + if (nsp && nsp[method]) { + Reflect.apply(nsp[method], null, []); + } + } + } catch(e) { + // socket.io throw a this.destroy of undefined? + console.error('disconnect', e); + } +}; + +/** + * trigger errors on all the namespace onError handler + * @param {object} ee Event Emitter + * @param {array} namespaces nsps string + * @param {string} message optional + * @return {void} + */ +function triggerNamespacesOnError(ee, namespaces, message) { + namespaces.forEach( function (namespace) { + ee.$call(createEvt(namespace, ERROR_PROP_NAME), [{ message: message, namespace: namespace }]); + }); +} + +// @TODO port what is in the ws-main-handler +var debugFn$1 = getDebug('client-event-handler'); + +/** + * A fake ee handler + * @param {string} namespace nsp + * @param {object} ee EventEmitter + * @return {void} + */ +var notLoginWsHandler = function (namespace, ee) { + ee.$only( + createEvt(namespace, EMIT_EVT), + function(resolverName, args) { + debugFn$1('noLoginHandler hijack the ws call', namespace, resolverName, args); + var error = { + message: NOT_LOGIN_ERR_MSG + }; + // It should just throw error here and should not call the result + // because that's channel for handling normal event not the fake one + ee.$call(createEvt(namespace, resolverName, ERROR_PROP_NAME), [error]); + // also trigger the result handler, but wrap inside the error key + ee.$call(createEvt(namespace, resolverName, RESULT_PROP_NAME), [{ error: error }]); + } + ); +}; + +/** + * centralize all the comm in one place + * @param {object} opts configuration + * @param {array} namespaces namespace(s) + * @param {object} ee Event Emitter instance + * @param {function} bindWsHandler binding the ee to ws + * @param {array} namespaces array of namespace available + * @param {object} nsps namespaced nsp + * @return {void} nothing + */ +function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) { + // loop + // @BUG for io this has to be in order the one with auth need to get call first + // The order of login is very import we need to run a waterfall here to make sure + // one is execute then the other + namespaces.forEach(function (namespace) { + if (nsps[namespace]) { + debugFn$1('call bindWsHandler', namespace); + var args = [namespace, nsps[namespace], ee]; + if (opts.serverType === SOCKET_IO) { + var nspSet = nspMap.nspSet; + args.push(nspSet[namespace]); + args.push(opts); + } + Reflect.apply(bindWsHandler, null, args); + } else { + // a dummy placeholder + notLoginWsHandler(namespace, ee); + } + }); + // this will be available regardless enableAuth + // because the server can log the client out + ee.$on(LOGOUT_EVENT_NAME, function() { + debugFn$1('LOGOUT_EVENT_NAME'); + // disconnect(nsps, opts.serverType) + // we need to issue error to all the namespace onError handler + triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME); + // rebind all of the handler to the fake one + namespaces.forEach( function (namespace) { + clearMainEmitEvt(ee, namespace); + // clear out the nsp + nsps[namespace] = false; + // add a NOT LOGIN error if call + notLoginWsHandler(namespace, ee); + }); + }); +} + +// take the ws reply data for use +var debugFn$2 = getDebug('extract-ws-payload'); + +var keys$1 = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]; + +/** + * @param {object} payload should be string when reply but could be transformed + * @return {boolean} true is OK + */ +var isWsReply = function (payload) { + var data = payload.data; + if (data) { + var result = keys$1.filter(function (key) { return isKeyInObject(data, key); }); + return (result.length === keys$1.length) ? data : false; + } + return false; +}; + +/** + * @param {object} payload This is the entire ws Event Object + * @return {object} false on failed + */ +var extractWsPayload = function (payload) { + var data = payload.data; + var json = isString$1(data) ? JSON.parse(data) : data; + // debugFn('extractWsPayload', json) + var fdata; + if ((fdata = isWsReply(json)) !== false) { + return { + resolverName: fdata[WS_EVT_NAME], + data: fdata[WS_DATA_NAME], + type: fdata[WS_REPLY_TYPE] + }; + } + throw new JsonqlError('payload can not be decoded', payload) +}; + +// the WebSocket main handler +var debugFn$3 = getDebug('ws-main-handler'); + +/** + * under extremely circumstances we might not even have a resolverName, then + * we issue a global error for the developer to catch it + * @param {object} ee event emitter + * @param {string} namespace nsp + * @param {string} resolverName resolver + * @param {object} json decoded payload or error object + */ +var errorTypeHandler = function (ee, namespace, resolverName, json) { + var evt = [namespace]; + if (resolverName) { + debugFn$3(("a global error on " + namespace)); + evt.push(resolverName); + } + evt.push(ERROR_PROP_NAME); + var evtName = Reflect.apply(createEvt, null, evt); + // test if there is a data field + var payload = json.data || json; + ee.$trigger(evtName, [payload]); +}; + +/** + * Binding the even to socket normally + * @param {string} namespace + * @param {object} ws the nsp + * @param {object} ee EventEmitter + * @return {object} promise resolve after the onopen event + */ +function wsMainHandlerAction(namespace, ws, ee) { + // send + ws.onopen = function() { + // we just call the onReady + ee.$call(READY_PROP_NAME, namespace); + // add listener + ee.$only( + createEvt(namespace, EMIT_EVT), + function(resolverName, args) { + debugFn$3('calling server', resolverName, args); + ws.send( + createQueryStr$1(resolverName, args) + ); + } + ); + }; + + // reply + ws.onmessage = function(payload) { + try { + var json = extractWsPayload(payload); + debugFn$3('Hear from server', json); + var resolverName = json.resolverName; + var type = json.type; + switch (type) { + case EMIT_REPLY_TYPE: + var r = ee.$trigger(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), [json]); + debugFn$3(MESSAGE_PROP_NAME, r); + break; + case ACKNOWLEDGE_REPLY_TYPE: + debugFn$3(RESULT_PROP_NAME, json); + var x = ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [json]); + debugFn$3('onResult add to event?', x); + break; + case ERROR_TYPE: + // this is handled error and we won't throw it + // we need to extract the error from json + errorTypeHandler(ee, namespace, resolverName, json); + break; + // @TODO there should be an error type instead of roll into the other two types? TBC + default: + // if this happen then we should throw it and halt the operation all together + debugFn$3('Unhandled event!', json); + errorTypeHandler(ee, namespace, resolverName, json); + // let error = {error: {'message': 'Unhandled event!', type}}; + // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error]) + } + } catch(e) { + errorTypeHandler(ee, namespace, false, e); + } + }; + // when the server close the connection + ws.onclose = function() { + debugFn$3('ws.onclose'); + // @TODO what to do with this + // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) + }; + // listen to the LOGOUT_EVENT_NAME + ee.$on(LOGOUT_EVENT_NAME, function close() { + try { + debugFn$3('terminate ws connection'); + ws.terminate(); + } catch(e) { + debugFn$3('terminate ws error', e); + } + }); +} + +// make this another standalone module +var debugFn$4 = getDebug('ws-create-client'); + +/** + * Because the nsps can be throw away so it doesn't matter the scope + * this will get reuse again + * @param {object} opts configuration + * @param {object} nspMap from contract + * @param {string|null} token whether we have the token at run time + * @return {object} nsps namespace with namespace as key + */ +var createNsps = function(opts, nspMap, token) { + var nspSet = nspMap.nspSet; + var publicNamespace = nspMap.publicNamespace; + var login = false; + var namespaces = []; + var nsps = {}; + // first we need to binding all the events handler + if (opts.enableAuth && opts.useJwt) { + login = true; // just saying we need to listen to login event + namespaces = getNamespaceInOrder(nspSet, publicNamespace); + nsps = namespaces.map(function (namespace, i) { + var obj, obj$1, obj$2; + + if (i === 0) { + if (token) { + opts.token = token; + return ( obj = {}, obj[namespace] = nspAuthClient(namespace, opts), obj ) + } + return ( obj$1 = {}, obj$1[namespace] = false, obj$1 ) + } + return ( obj$2 = {}, obj$2[namespace] = nspClient(namespace, opts), obj$2 ) + }).reduce(function (first, next) { return Object.assign(first, next); }, {}); + } else { + var namespace = getNameFromPayload$1(nspSet); + namespaces.push(namespace); + // standard without login + // the stock version should not have a namespace + nsps[namespace] = nspClient(false, opts); + } + // return + return { nsps: nsps, namespaces: namespaces, login: login } +}; + +/** + * create a ws client + * @param {object} opts configuration + * @param {object} nspMap namespace with resolvers + * @param {object} ee EventEmitter to pass through + * @return {object} what comes in what goes out + */ +function createClient(opts, nspMap, ee) { + // arguments that don't change + var args = [opts, nspMap, ee, wsMainHandlerAction]; + // now create the nsps + var ref = createNsps(opts, nspMap, opts.token); + var nsps = ref.nsps; + var namespaces = ref.namespaces; + var login = ref.login; + // binding the listeners - and it will listen to LOGOUT event + // to unbind itself, and the above call will bind it again + Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])); + // setup listener + if (login) { + ee.$only(LOGIN_EVENT_NAME, function(token) { + disconnect(nsps, JS_WS_NAME); + // @TODO should we trigger error on this one? + // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME) + clearMainEmitEvt(ee, namespaces); + debugFn$4('LOGIN_EVENT_NAME', token); + var newNsps = createNsps(opts, nspMap, token); + // rebind it + Reflect.apply( + clientEventHandler, + null, + args.concat([newNsps.namespaces, newNsps.nsps]) + ); + }); + } + // return what input + return { opts: opts, nspMap: nspMap, ee: ee } +} + +// we only need to export one interface from now on + +var debugFn$5 = getDebug('io-main-handler'); + +/** + * @param {object} ee Event Emitter + * @param {string} namespace namespace of this nsp + * @param {string} resolverName resolver to handle this call + * @return {function} capture the result + */ +var resultHandler = function (ee, namespace, resolverName, evt) { + if ( evt === void 0 ) evt = RESULT_PROP_NAME; + + return function (result) { + ee.$trigger(createEvt(namespace, resolverName, evt), [result]); + } +}; + +/** + * @param {object} nspSet resolver list + * @param {object} nsp nsp instance + * @param {object} ee Event Emitter + * @param {string} namespace name of this nsp + * @return {void} + */ +var createResolverListener = function (nspSet, nsp, ee, namespace) { + for (var resolverName in nspSet) { + nsp.on( + resolverName, + resultHandler(ee, namespace, resolverName, MESSAGE_PROP_NAME) + ); + } +}; + +/** + * @param {object} nsp instance + * @param {object} ee Event Emitter + * @param {string} namespace name of this nsp + * @return {void} + */ +var mainEventHandler = function (nsp, ee, namespace) { + ee.$only( + createEvt(namespace, EMIT_EVT), + function resolverEmitHandler(resolverName, args) { + debugFn$5('mainEventHandler', resolverName, args); + nsp.emit( + resolverName, + formatPayload(args), + resultHandler(ee, namespace, resolverName) + ); + } + ); +}; + +/** + * it makes no different at this point if we know its connection establish or not + * We should actually know this before hand before we call here + * @param {string} namespace of this client + * @param {object} socket this is the resolved nsp connection object + * @param {object} ee Event Emitter + * @param {object} nspSet the list of resolvers + * @param {object} opts configuration + */ +function ioMainHandler(namespace, socket, ee, nspSet, opts) { + // the main listener for all the client resolvers + mainEventHandler(socket, ee, namespace); + // it doesn't make much different between inside the connect or not + // loop through to create the listeners + createResolverListener(nspSet, socket, ee, namespace); + //@TODO next we need to add a ERROR handler + // The server side is not implementing a global ERROR call yet + // and the result or message error will be handle individually by their callback + // listen to the server close event + socket.on('disconnect', function disconnect() { + debugFn$5('io.disconnect'); + // TBC what to do with this + // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) + }); + // listen to the logout event + ee.$on(LOGOUT_EVENT_NAME, function logoutHandler() { + try { + debugFn$5('terminate ws connection'); + socket.close(); + } catch(e) { + debugFn$5('terminate ws error', e); + } + }); + // the last one to fire + ee.$trigger(READY_PROP_NAME, namespace); +} + +// this will create the socket.io client +var debugFn$6 = getDebug('io-create-client'); + +// just to make it less ugly +var mapNsps = function (nsps, namespaces) { return nsps + .map(function (nsp, i) { + var obj; + + return (( obj = {}, obj[namespaces[i]] = nsp, obj )); + }) + .reduce(function (last, next) { return Object.assign(last,next); }, {}); }; + +/** + * This one will run the create nsps in sequence and make sure + * the auth one connect before we call the others + * @param {object} opts configuration + * @param {object} nspMap contract map + * @param {string} token validation + * @return {object} promise resolve with namespaces, nsps in same order array + */ +var createAuthNsps = function(opts, nspMap, token, namespaces) { + var publicNamespace = nspMap.publicNamespace; + opts.token = token; + var p1 = function () { return nspAuthClient(namespaces[0], opts); }; + var p2 = function () { return nspClient(namespaces[1], opts); }; + return chainPromises([p1(), p2()]) + .then(function (nsps) { return ({ + nsps: mapNsps(nsps, namespaces), + namespaces: namespaces, + login: false + }); }) +}; + +/** + * Because the nsps can be throw away so it doesn't matter the scope + * this will get reuse again + * @param {object} opts configuration + * @param {object} nspMap from contract + * @param {string|null} token whether we have the token at run time + * @return {object} nsps namespace with namespace as key + */ +var createNsps$1 = function(opts, nspMap, token) { + var nspSet = nspMap.nspSet; + var publicNamespace = nspMap.publicNamespace; + var login = false; + // first we need to binding all the events handler + if (opts.enableAuth && opts.useJwt) { + var namespaces = getNamespaceInOrder(nspSet, publicNamespace); + debugFn$6('namespaces', namespaces); + login = opts.useJwt; // just saying we need to listen to login event + if (token) { + debugFn$6('call createAuthNsps'); + return createAuthNsps(opts, nspMap, token, namespaces) + } + debugFn$6('init with a placeholder'); + return nspClient(publicNamespace, opts) + .then(function (nsp) { + var obj; + + return ({ + nsps: ( obj = {}, obj[ publicNamespace ] = nsp, obj[ namespaces[0] ] = false, obj ), + namespaces: namespaces, + login: login + }); + }) + } + // standard without login + // the stock version should not have a namespace + return nspClient(false, opts) + .then(function (nsp) { + var obj; + + return ({ + nsps: ( obj = {}, obj[publicNamespace] = nsp, obj ), + namespaces: [publicNamespace], + login: login + }); + }) +}; + + + +/** + * This is just copy of the ws version we need to figure + * out how to deal with the roundtrip login later + * @param {object} opts configuration + * @param {object} nspMap namespace with resolvers + * @param {object} ee EventEmitter to pass through + * @return {object} what comes in what goes out + */ +function createClient$1(opts, nspMap, ee) { + // arguments don't change + var args = [opts, nspMap, ee, ioMainHandler]; + return createNsps$1(opts, nspMap, opts.token) + .then( function (ref) { + var nsps = ref.nsps; + var namespaces = ref.namespaces; + var login = ref.login; + + // binding the listeners - and it will listen to LOGOUT event + // to unbind itself, and the above call will bind it again + Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])); + if (login) { + ee.$only(LOGIN_EVENT_NAME, function(token) { + // here we should disconnect all the previous nsps + disconnect(nsps); + // first trigger a LOGOUT event to unbind ee to ws + // ee.$trigger(LOGOUT_EVENT_NAME) // <-- this seems to cause a lot of problems + clearMainEmitEvt(ee, namespaces); + debugFn$6('LOGIN_EVENT_NAME'); + createNsps$1(opts, nspMap, token) + .then(function (newNsps) { + // rebind it + Reflect.apply( + clientEventHandler, + null, + args.concat([newNsps.namespaces, newNsps.nsps]) + ); + }); + }); + } + // return this will also works because the outter call are in promise chain + return { opts: opts, nspMap: nspMap, ee: ee } + }) +} + +/** + * get the create client instance function + * @param {string} type of client + * @return {function} the actual methods + * @public + */ +function createSocketClient(opts, nspMap, ee) { + switch (opts.serverType) { + case SOCKET_IO: + return createClient$1(opts, nspMap, ee) + case WS: + return createClient(opts, nspMap, ee) + default: + throw new JsonqlError(SOCKET_NOT_DEFINE_ERR) + } +} + +// generator resolvers +var EMIT_EVT$1 = EMIT_EVT; +var UNKNOWN_RESULT$1 = UNKNOWN_RESULT; +var MY_NAMESPACE$1 = MY_NAMESPACE; +var debugFn$7 = getDebug('generator'); + +/** + * prepare the methods + * @param {object} opts configuration + * @param {object} nspMap resolvers index by their namespace + * @param {object} ee EventEmitter + * @return {object} of resolvers + * @public + */ +function generator(opts, nspMap, ee) { + var obj = {}; + var nspSet = nspMap.nspSet; + for (var namespace in nspSet) { + var list = nspSet[namespace]; + for (var resolverName in list) { + var params = list[resolverName]; + var fn = createResolver(ee, namespace, resolverName, params); + obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee); + } + } + // add error handler + createNamespaceErrorHandler(obj, ee, nspSet); + // add onReady handler + createOnReadyhandler(obj, ee); + // Auth related methods + createAuthMethods(obj, ee, opts); + // this is a helper method for the developer to know the namespace inside + obj.getNsp = function () { + return Object.keys(nspSet) + }; + // output + return obj; +} + +/** + * create the actual function to send message to server + * @param {object} ee EventEmitter instance + * @param {string} namespace this resolver end point + * @param {string} resolverName name of resolver as event name + * @param {object} params from contract + * @return {function} resolver + */ +function createResolver(ee, namespace, resolverName, params) { + // note we pass the new withResult=true option + return function() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return validateAsync$1(args, params.params, true) + .then( function (_args) { return actionCall(ee, namespace, resolverName, _args); } ) + .catch(finalCatch) + } +} + +/** + * just wrapper + * @param {object} ee EventEmitter + * @param {string} namespace where this belongs + * @param {string} resolverName resolver + * @param {array} args arguments + * @return {void} nothing + */ +function actionCall(ee, namespace, resolverName, args) { + if ( args === void 0 ) args = []; + + debugFn$7(("actionCall: " + namespace + " " + resolverName), args); + ee.$trigger(createEvt(namespace, EMIT_EVT$1), [ + resolverName, + toArray$1(args) + ]); +} + +/** + * break out to use in different places to handle the return from server + * @param {object} data from server + * @param {function} resolver from promise + * @param {function} rejecter from promise + * @return {void} nothing + */ +function respondHandler(data, resolver, rejecter) { + if (isKeyInObject(data, 'error')) { + debugFn$7('rejecter called', data.error); + rejecter(data.error); + } else if (isKeyInObject(data, 'data')) { + debugFn$7('resolver called', data.data); + resolver(data.data); + } else { + debugFn$7('UNKNOWN_RESULT', data); + rejecter({message: UNKNOWN_RESULT$1, error: data}); + } +} + +/** + * Add extra property to the resolver + * @param {string} namespace where this belongs + * @param {string} resolverName name as event name + * @param {object} params from contract + * @param {function} fn resolver function + * @param {object} ee EventEmitter + * @return {function} resolver + */ +var setupResolver = function (namespace, resolverName, params, fn, ee) { + // also need to setup a getter to get back the namespace of this resolver + if (Object.getOwnPropertyDescriptor(fn, MY_NAMESPACE$1) === undefined) { + Object.defineProperty(fn, MY_NAMESPACE$1, { + value: namespace, + writeable: false + }); + } + // onResult handler + if (Object.getOwnPropertyDescriptor(fn, RESULT_PROP_NAME) === undefined) { + Object.defineProperty(fn, RESULT_PROP_NAME, { + set: function(resultCallback) { + if (typeof resultCallback === 'function') { + ee.$only( + createEvt(namespace, resolverName, RESULT_PROP_NAME), + function resultHandler(result) { + respondHandler(result, resultCallback, function (error) { + ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error); + }); + } + ); + } + }, + get: function() { + return null; + } + }); + } + // we do need to add the send prop back because it's the only way to deal with + // bi-directional data stream + if (Object.getOwnPropertyDescriptor(fn, MESSAGE_PROP_NAME) === undefined) { + Object.defineProperty(fn, MESSAGE_PROP_NAME, { + set: function(messageCallback) { + // we expect this to be a function + if (typeof messageCallback === 'function') { + // did that add to the callback + var onMessageCallback = function (args) { + respondHandler(args, messageCallback, function (error) { + ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error); + }); + }; + // register the handler for this message event + ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback); + } + }, + get: function() { + return null; // just return nothing + } + }); + } + // add an ERROR_PROP_NAME handler + if (Object.getOwnPropertyDescriptor(fn, ERROR_PROP_NAME) === undefined) { + Object.defineProperty(fn, ERROR_PROP_NAME, { + set: function(resolverErrorHandler) { + if (typeof resolverErrorHandler === 'function') { + // please note ERROR_PROP_NAME can add multiple listners + ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler); + } + }, + get: function() { + return null; + } + }); + } + // pairing with the server vesrion SEND_MSG_PROP_NAME + if (Object.getOwnPropertyDescriptor(fn, SEND_MSG_PROP_NAME) === undefined) { + Object.defineProperty(fn, SEND_MSG_PROP_NAME, { + set: function(messagePayload) { + var result = validateSync$1(toArray$1(messagePayload), params.params, true); + // here is the different we don't throw erro instead we trigger an + // onError + if (result[ERROR_KEY] && result[ERROR_KEY].length) { + ee.$call( + createEvt(namespace, resolverName, ERROR_PROP_NAME), + [JsonqlValidationError(resolverName, result[ERROR_KEY])] + ); + } else { + // there is no return only an action call + actionCall(ee, namespace, resolverName, result[DATA_KEY]); + } + }, + get: function() { + return null; // just return nothing + } + }); + } + return fn; +}; + +/** + * The problem is the namespace can have more than one + * and we only have on onError message + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} nspSet namespace keys + * @return {void} + */ +var createNamespaceErrorHandler = function (obj, ee, nspSet) { + // using the onError as name + // @TODO we should follow the convention earlier + // make this a setter for the obj itself + if (Object.getOwnPropertyDescriptor(obj, ERROR_PROP_NAME) === undefined) { + Object.defineProperty(obj, ERROR_PROP_NAME, { + set: function(namespaceErrorHandler) { + if (typeof namespaceErrorHandler === 'function') { + // please note ERROR_PROP_NAME can add multiple listners + for (var namespace in nspSet) { + // this one is very tricky, we need to make sure the trigger is calling + // with the namespace as well as the error + ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler); + } + } + }, + get: function() { + return null; + } + }); + } +}; + +/** + * This event will fire when the socket.io.on('connection') and ws.onopen + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} nspSet namespace keys + * @return {void} + */ +var createOnReadyhandler = function (obj, ee, nspSet) { + if (Object.getOwnPropertyDescriptor(obj, READY_PROP_NAME) === undefined) { + Object.defineProperty(obj, READY_PROP_NAME, { + set: function(onReadyCallback) { + if (typeof onReadyCallback === 'function') { + // reduce it down to just one flat level + var result = ee.$on(READY_PROP_NAME, onReadyCallback); + } + }, + get: function() { + return null; + } + }); + } +}; + +/** + * Create auth related methods + * @param {object} obj the client itself + * @param {object} ee Event Emitter + * @param {object} opts configuration + * @return {void} + */ +var createAuthMethods = function (obj, ee, opts) { + if (opts.enableAuth) { + // create an additonal login handler + // we require the token + obj[opts.loginHandlerName] = function (token) { + debugFn$7(opts.loginHandlerName, token); + if (token && isString$1(token)) { + return ee.$trigger(LOGIN_EVENT_NAME, [token]) + } + throw new JsonqlValidationError(opts.loginHandlerName) + }; + // logout event handler + obj[opts.logoutHandlerName] = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + ee.$trigger(LOGOUT_EVENT_NAME, args); + }; + } +}; + +// main api to get the ws-client + +/** + * The main interface to create the wsClient for use + * @param {function} clientGenerator this is an internal way to generate node or browser client + * @return {function} wsClient + * @public + */ +function main(clientGenerator) { + /** + * @param {object} config configuration + * @param {object} [eventEmitter=false] this will be the bridge between clients + * @return {object} wsClient + */ + var wsClient = function (config, eventEmitter) { + if ( eventEmitter === void 0 ) eventEmitter = false; + + return checkOptions(config) + .then(function (opts) { return ({ + opts: opts, + nspMap: processContract(opts), + ee: eventEmitter || new JsonqlWsEvt() + }); } + ) + .then(clientGenerator) + .then( + function (ref) { + var opts = ref.opts; + var nspMap = ref.nspMap; + var ee = ref.ee; + + return createSocketClient(opts, nspMap, ee); + } + ) + .then( + function (ref) { + var opts = ref.opts; + var nspMap = ref.nspMap; + var ee = ref.ee; + + return generator(opts, nspMap, ee); + } + ) + .catch(function (err) { + console.error('jsonql-ws-client init error', err); + }) + }; + // use the Object.addProperty trick + Object.defineProperty(wsClient, 'CLIENT_TYPE_INFO', { + value: 'version: 1.0.0-beta.1 module: cjs', + writable: false + }); + return wsClient; +} + +module.exports = main; diff --git a/packages/ws-client/beta/src/utils/check-options.js b/packages/ws-client/beta/src/utils/check-options.js new file mode 100644 index 00000000..045a2a88 --- /dev/null +++ b/packages/ws-client/beta/src/utils/check-options.js @@ -0,0 +1,66 @@ +// create options +import { createConfig, checkConfigAsync, isContract, isNotEmpty } from 'jsonql-params-validator' +import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors' +import { + STRING_TYPE, + BOOLEAN_TYPE, + OBJECT_TYPE, + ENUM_KEY, + CHECKER_KEY, + JSONQL_PATH, + ISSUER_NAME, + LOGOUT_NAME +} from 'jsonql-constants' +import { SOCKET_IO, WS, AVAILABLE_SERVERS } from './constants' +import getDebug from './get-debug' +const debug = getDebug('check-options') + +const fixWss = (url, serverType) => { + // ws only allow ws:// path + if (serverType===WS) { + return url.replace('http://', 'ws://') + } + return url; +} + +const getHostName = () => ( + [window.location.protocol, window.location.host].join('//') +) + +const constProps = { + // this will be the switcher! + nspClient: null, + nspAuthClient: null, + // contructed path + wssPath: '' +} + +const defaultOptions = { + loginHandlerName: createConfig(ISSUER_NAME, [STRING_TYPE]), + logoutHandlerName: createConfig(LOGOUT_NAME, [STRING_TYPE]), + // we will use this for determine the socket.io client type as well + useJwt: createConfig(false, [BOOLEAN_TYPE, STRING_TYPE]), + hostname: createConfig(false, [STRING_TYPE]), + namespace: createConfig(JSONQL_PATH, [STRING_TYPE]), + wsOptions: createConfig({transports: ['websocket'], 'force new connection' : true}, [OBJECT_TYPE]), + serverType: createConfig(SOCKET_IO, [STRING_TYPE], {[ENUM_KEY]: AVAILABLE_SERVERS}), + // we require the contract already generated and pass here + contract: createConfig({}, [OBJECT_TYPE], {[CHECKER_KEY]: isContract}), + enableAuth: createConfig(false, [BOOLEAN_TYPE]), + token: createConfig(false, [STRING_TYPE]) +} +// export +export default function checkOptions(config) { + return checkConfigAsync(config, defaultOptions, constProps) + .then(opts => { + if (!opts.hostname) { + opts.hostname = getHostName() + } + // @TODO the contract now will supply the namespace information + // and we need to use that to group the namespace call + opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType) + + debug('opts', opts) + return opts; + }) +} diff --git a/packages/ws-client/beta/src/utils/client-generator.js b/packages/ws-client/beta/src/utils/client-generator.js new file mode 100644 index 00000000..a7f7a6c9 --- /dev/null +++ b/packages/ws-client/beta/src/utils/client-generator.js @@ -0,0 +1,46 @@ +// generate the web socket connect client for browser +import { + socketIoRoundtripLogin, + socketIoClientAsync, + socketIoHandshakeLogin, + wsAuthClient, + wsClient +} from 'jsonql-jwt' + +import { isString } from 'jsonql-params-validator' +import { JsonqlError } from 'jsonql-errors' +import { SOCKET_IO, WS } from './constants' +// import { IO_ROUNDTRIP_LOGIN, IO_HANDSHAKE_LOGIN } from 'jsonql-constants' +import getDebug from './get-debug' +const debug = getDebug('client-generator') + +/** + * create the web socket client + * @param {object} payload passing + * @return {object} just mutate it then pass it on + */ +export default function clientGenerator({opts, nspMap, ee}) { + switch (opts.serverType) { + case SOCKET_IO: + opts.nspClient = (...args) => ( + Reflect.apply(socketIoClientAsync, null, [io, ...args]) + ) + if (isString(opts.useJwt)) { + opts.nspAuthClient = (...args) => ( + Reflect.apply(socketIoRoundtripLogin, null, [io, ...args]) + ) + } else { + opts.nspAuthClient = (...args) => ( + Reflect.apply(socketIoHandshakeLogin, null, [io, ...args]) + ) + } + break; + case WS: + opts.nspClient = wsClient; + opts.nspAuthClient = wsAuthClient; + break; + default: + throw new JsonqlError(`Unknown serverType: ${opts.serverType}`) + } + return {opts, nspMap, ee} +} diff --git a/packages/ws-client/beta/src/utils/constants.js b/packages/ws-client/beta/src/utils/constants.js new file mode 100644 index 00000000..928a4304 --- /dev/null +++ b/packages/ws-client/beta/src/utils/constants.js @@ -0,0 +1,49 @@ +// constants + +import { + EMIT_REPLY_TYPE, + JS_WS_SOCKET_IO_NAME, + JS_WS_NAME, + MESSAGE_PROP_NAME, + RESULT_PROP_NAME +} from 'jsonql-constants' + +const SOCKET_IO = JS_WS_SOCKET_IO_NAME; +const WS = JS_WS_NAME; + +const AVAILABLE_SERVERS = [SOCKET_IO, WS] + +const SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'; + +const SERVER_NOT_SUPPORT_ERR = 'is not supported server name!'; + +const MISSING_PROP_ERR = 'Missing property in contract!'; + +const UNKNOWN_CLIENT_ERR = 'Unknown client type!'; + +const EMIT_EVT = EMIT_REPLY_TYPE; + +const NAMESPACE_KEY = 'namespaceMap'; + +const UNKNOWN_RESULT = 'UKNNOWN RESULT!'; + +const NOT_ALLOW_OP = 'This operation is not allow!'; + +const MY_NAMESPACE = 'myNamespace' + +export { + SOCKET_IO, + WS, + AVAILABLE_SERVERS, + SOCKET_NOT_DEFINE_ERR, + SERVER_NOT_SUPPORT_ERR, + MISSING_PROP_ERR, + UNKNOWN_CLIENT_ERR, + EMIT_EVT, + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + NAMESPACE_KEY, + UNKNOWN_RESULT, + NOT_ALLOW_OP, + MY_NAMESPACE +} diff --git a/packages/ws-client/beta/src/utils/create-nsp-client.js b/packages/ws-client/beta/src/utils/create-nsp-client.js new file mode 100644 index 00000000..9b656813 --- /dev/null +++ b/packages/ws-client/beta/src/utils/create-nsp-client.js @@ -0,0 +1,34 @@ +// since both the ws and io version are +// pre-defined in the client-generator +// and this one will have the same parameters +// and the callback is identical +import getDebug from './get-debug' +const debugFn = getDebug('create-nsp-client') +/** + * wrapper method to create a nsp without login + * @param {string|boolean} namespace namespace url could be false + * @param {object} opts configuration + * @return {object} ws client instance + */ +const nspClient = (namespace, opts) => { + const { wssPath, wsOptions, hostname } = opts; + const url = namespace ? [hostname, namespace].join('/') : wssPath; + return opts.nspClient(url, wsOptions) +} + +/** + * wrapper method to create a nsp with token auth + * @param {string} namespace namespace url + * @param {object} opts configuration + * @return {object} ws client instance + */ +const nspAuthClient = (namespace, opts) => { + const { wssPath, token, wsOptions, hostname } = opts; + const url = namespace ? [hostname, namespace].join('/') : wssPath; + return opts.nspAuthClient(url, token, wsOptions) +} + +export { + nspClient, + nspAuthClient +} diff --git a/packages/ws-client/beta/src/utils/ee.js b/packages/ws-client/beta/src/utils/ee.js new file mode 100644 index 00000000..dcf92620 --- /dev/null +++ b/packages/ws-client/beta/src/utils/ee.js @@ -0,0 +1,14 @@ +import getDebug from './get-debug' +// this will generate a event emitter and will be use everywhere +import NBEventService from 'nb-event-service' +// create a clone version so we know which one we actually is using +export default class JsonqlWsEvt extends NBEventService { + + constructor() { + super({logger: getDebug('nb-event-service')}) + } + + get name() { + return'jsonql-ws-client' + } +} diff --git a/packages/ws-client/beta/src/utils/get-debug.js b/packages/ws-client/beta/src/utils/get-debug.js new file mode 100644 index 00000000..fec2517d --- /dev/null +++ b/packages/ws-client/beta/src/utils/get-debug.js @@ -0,0 +1,22 @@ + +import debug from 'debug' +/** + * Try to normalize it to use between browser and node + * @param {string} name for the debug output + * @return {function} debug + */ +const getDebug = name => { + if (debug) { + return debug('jsonql-ws-client').extend(name) + } + return (...args) => { + console.info.apply(null, [name].concat(args)); + } +} +try { + if (window && window.localStorage) { + localStorage.setItem('DEBUG', 'jsonql-ws-client*'); + } +} catch(e) {} +// export it +export default getDebug; diff --git a/packages/ws-client/beta/src/utils/get-namespace-in-order.js b/packages/ws-client/beta/src/utils/get-namespace-in-order.js new file mode 100644 index 00000000..823a6256 --- /dev/null +++ b/packages/ws-client/beta/src/utils/get-namespace-in-order.js @@ -0,0 +1,20 @@ + + +/** + * Got to make sure the connection order otherwise + * it will hang + * @param {object} nspSet contract + * @param {string} publicNamespace like the name said + * @return {array} namespaces in order + */ +export default function getNamespaceInOrder(nspSet, publicNamespace) { + let names = []; // need to make sure the order! + for (let namespace in nspSet) { + if (namespace === publicNamespace) { + names[1] = namespace; + } else { + names[0] = namespace; + } + } + return names; +} diff --git a/packages/ws-client/beta/src/utils/index.js b/packages/ws-client/beta/src/utils/index.js new file mode 100644 index 00000000..479c442b --- /dev/null +++ b/packages/ws-client/beta/src/utils/index.js @@ -0,0 +1,74 @@ +// export the util methods +import { QUERY_ARG_NAME, JS_WS_SOCKET_IO_NAME } from 'jsonql-constants' +import getNamespaceInOrder from './get-namespace-in-order' +import checkOptions from './check-options' +import ee from './ee' +import * as constants from './constants' +import getDebug from './get-debug' + +import processContract from './process-contract' +import { isArray } from 'jsonql-params-validator' + +const toArray = (arg) => isArray(arg) ? arg : [arg]; + +/** + * very simple tool to create the event name + * @param {string} [...args] spread + * @return {string} join by _ + */ +const createEvt = (...args) => args.join('_') + +/** + * Unbind the event + * @param {object} ee EventEmitter + * @param {string} namespace + * @return {void} + */ +const clearMainEmitEvt = (ee, namespace) => { + let nsps = isArray(namespace) ? namespace : [namespace] + nsps.forEach(n => { + ee.$off(createEvt(n, constants.EMIT_EVT)) + }) +} + +/** + * @param {*} args arguments to send + *@return {object} formatted payload + */ +const formatPayload = (args) => ( + { [QUERY_ARG_NAME]: args } +) + +/** + * @param {object} nsps namespace as key + * @param {string} type of server + */ +const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => { + try { + const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate'; + for (let namespace in nsps) { + let nsp = nsps[namespace] + if (nsp && nsp[method]) { + Reflect.apply(nsp[method], null, []) + } + } + } catch(e) { + // socket.io throw a this.destroy of undefined? + console.error('disconnect', e) + } +} + + +export { + getNamespaceInOrder, + createEvt, + clearMainEmitEvt, + checkOptions, + ee, + constants, + getDebug, + processContract, + toArray, + formatPayload, + disconnect +} diff --git a/packages/ws-client/beta/src/utils/process-contract.js b/packages/ws-client/beta/src/utils/process-contract.js new file mode 100644 index 00000000..7ec6a855 --- /dev/null +++ b/packages/ws-client/beta/src/utils/process-contract.js @@ -0,0 +1,41 @@ +// mapping the resolver to their respective nsp + +import { JSONQL_PATH } from 'jsonql-constants' +import { groupByNamespace } from 'jsonql-jwt' +import { JsonqlResolverNotFoundError } from 'jsonql-errors' + +import { MISSING_PROP_ERR } from './constants' +import getDebug from './get-debug' +const debug = getDebug('process-contract') + +/** + * Just make sure the object contain what we are looking for + * @param {object} opts configuration from checkOptions + * @return {object} the target content + */ +const getResolverList = contract => { + if (contract) { + const { socket } = contract; + if (socket) { + return socket; + } + } + throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR) +} + +/** + * process the contract first + * @param {object} opts configuration + * @return {object} sorted list + */ +export default function processContract(opts) { + const { contract, enableAuth } = opts; + if (enableAuth) { + return groupByNamespace(contract) + } + return { + nspSet: { [JSONQL_PATH]: getResolverList(contract) }, + publicNamespace: JSONQL_PATH, + size: 1 // this prop is pretty meaningless now + } +} diff --git a/packages/ws-client/beta/src/utils/trigger-namespaces-on-error.js b/packages/ws-client/beta/src/utils/trigger-namespaces-on-error.js new file mode 100644 index 00000000..59409c81 --- /dev/null +++ b/packages/ws-client/beta/src/utils/trigger-namespaces-on-error.js @@ -0,0 +1,15 @@ + +import { ERROR_PROP_NAME } from 'jsonql-constants' +import { createEvt } from './index' +/** + * trigger errors on all the namespace onError handler + * @param {object} ee Event Emitter + * @param {array} namespaces nsps string + * @param {string} message optional + * @return {void} + */ +export default function triggerNamespacesOnError(ee, namespaces, message) { + namespaces.forEach( namespace => { + ee.$call(createEvt(namespace, ERROR_PROP_NAME), [{ message, namespace }]) + }) +} diff --git a/packages/ws-client/beta/src/ws/create-client.js b/packages/ws-client/beta/src/ws/create-client.js new file mode 100644 index 00000000..d026e70c --- /dev/null +++ b/packages/ws-client/beta/src/ws/create-client.js @@ -0,0 +1,85 @@ +// make this another standalone module +import { getNameFromPayload } from 'jsonql-params-validator' +import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants' +import { nspClient, nspAuthClient } from '../utils/create-nsp-client' +// this become the cb +import clientEventHandler from '../client-event-handler' +import triggerNamespacesOnError from '../utils/trigger-namespaces-on-error' +// move this up one level from client-event-handler +import wsMainHandler from './ws-main-handler' +import { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils' +const debugFn = getDebug('ws-create-client') + +/** + * Because the nsps can be throw away so it doesn't matter the scope + * this will get reuse again + * @param {object} opts configuration + * @param {object} nspMap from contract + * @param {string|null} token whether we have the token at run time + * @return {object} nsps namespace with namespace as key + */ +const createNsps = function(opts, nspMap, token) { + let { nspSet, publicNamespace } = nspMap; + let login = false; + let namespaces = []; + let nsps = {}; + // first we need to binding all the events handler + if (opts.enableAuth && opts.useJwt) { + login = true; // just saying we need to listen to login event + namespaces = getNamespaceInOrder(nspSet, publicNamespace) + nsps = namespaces.map((namespace, i) => { + if (i === 0) { + if (token) { + opts.token = token; + return {[namespace]: nspAuthClient(namespace, opts)} + } + return {[namespace]: false} + } + return {[namespace]: nspClient(namespace, opts)} + }).reduce((first, next) => Object.assign(first, next), {}) + } else { + let namespace = getNameFromPayload(nspSet) + namespaces.push(namespace) + // standard without login + // the stock version should not have a namespace + nsps[namespace] = nspClient(false, opts) + } + // return + return { nsps, namespaces, login } +} + +/** + * create a ws client + * @param {object} opts configuration + * @param {object} nspMap namespace with resolvers + * @param {object} ee EventEmitter to pass through + * @return {object} what comes in what goes out + */ +export default function createClient(opts, nspMap, ee) { + // arguments that don't change + let args = [opts, nspMap, ee, wsMainHandler] + // now create the nsps + let { nsps, namespaces, login } = createNsps(opts, nspMap, opts.token) + // binding the listeners - and it will listen to LOGOUT event + // to unbind itself, and the above call will bind it again + Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])) + // setup listener + if (login) { + ee.$only(LOGIN_EVENT_NAME, function(token) { + disconnect(nsps, JS_WS_NAME) + // @TODO should we trigger error on this one? + // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME) + clearMainEmitEvt(ee, namespaces) + debugFn('LOGIN_EVENT_NAME', token) + let newNsps = createNsps(opts, nspMap, token) + // rebind it + Reflect.apply( + clientEventHandler, + null, + args.concat([newNsps.namespaces, newNsps.nsps]) + ) + }) + } + // return what input + return { opts, nspMap, ee } +} diff --git a/packages/ws-client/beta/src/ws/extract-ws-payload.js b/packages/ws-client/beta/src/ws/extract-ws-payload.js new file mode 100644 index 00000000..1a8412ba --- /dev/null +++ b/packages/ws-client/beta/src/ws/extract-ws-payload.js @@ -0,0 +1,43 @@ +// take the ws reply data for use +import { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants' +import { isString, isKeyInObject } from 'jsonql-params-validator' +import { JsonqlError, clientErrorsHandler } from 'jsonql-errors' + +import getDebug from '../utils/get-debug' +const debugFn = getDebug('extract-ws-payload') + +const keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ] + +/** + * @param {object} payload should be string when reply but could be transformed + * @return {boolean} true is OK + */ +const isWsReply = payload => { + const { data } = payload; + if (data) { + let result = keys.filter(key => isKeyInObject(data, key)) + return (result.length === keys.length) ? data : false; + } + return false; +} + +/** + * @param {object} payload This is the entire ws Event Object + * @return {object} false on failed + */ +const extractWsPayload = payload => { + const { data } = payload; + let json = isString(data) ? JSON.parse(data) : data; + // debugFn('extractWsPayload', json) + let fdata; + if ((fdata = isWsReply(json)) !== false) { + return { + resolverName: fdata[WS_EVT_NAME], + data: fdata[WS_DATA_NAME], + type: fdata[WS_REPLY_TYPE] + }; + } + throw new JsonqlError('payload can not be decoded', payload) +} +// export it +export default extractWsPayload diff --git a/packages/ws-client/beta/src/ws/index.js b/packages/ws-client/beta/src/ws/index.js new file mode 100644 index 00000000..ac03c307 --- /dev/null +++ b/packages/ws-client/beta/src/ws/index.js @@ -0,0 +1,5 @@ +// we only need to export one interface from now on + +import createClient from './create-client' + +export default createClient diff --git a/packages/ws-client/beta/src/ws/ws-main-handler.js b/packages/ws-client/beta/src/ws/ws-main-handler.js new file mode 100644 index 00000000..73b7582b --- /dev/null +++ b/packages/ws-client/beta/src/ws/ws-main-handler.js @@ -0,0 +1,116 @@ +// the WebSocket main handler +import { + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + EMIT_EVT +} from '../utils/constants' +import { + ERROR_PROP_NAME, + LOGIN_EVENT_NAME, + LOGOUT_EVENT_NAME, + ACKNOWLEDGE_REPLY_TYPE, + EMIT_REPLY_TYPE, + ERROR_TYPE, + READY_PROP_NAME +} from 'jsonql-constants' + +import extractWsPayload from './extract-ws-payload' +import { createQueryStr } from 'jsonql-params-validator' + +import { getDebug, createEvt } from '../utils' +const debugFn = getDebug('ws-main-handler') + +/** + * under extremely circumstances we might not even have a resolverName, then + * we issue a global error for the developer to catch it + * @param {object} ee event emitter + * @param {string} namespace nsp + * @param {string} resolverName resolver + * @param {object} json decoded payload or error object + */ +const errorTypeHandler = (ee, namespace, resolverName, json) => { + let evt = [namespace] + if (resolverName) { + debugFn(`a global error on ${namespace}`) + evt.push(resolverName) + } + evt.push(ERROR_PROP_NAME) + let evtName = Reflect.apply(createEvt, null, evt) + // test if there is a data field + let payload = json.data || json; + ee.$trigger(evtName, [payload]) +} + +/** + * Binding the even to socket normally + * @param {string} namespace + * @param {object} ws the nsp + * @param {object} ee EventEmitter + * @return {object} promise resolve after the onopen event + */ +export default function wsMainHandlerAction(namespace, ws, ee) { + // send + ws.onopen = function() { + // we just call the onReady + ee.$call(READY_PROP_NAME, namespace) + // add listener + ee.$only( + createEvt(namespace, EMIT_EVT), + function(resolverName, args) { + debugFn('calling server', resolverName, args) + ws.send( + createQueryStr(resolverName, args) + ) + } + ) + } + + // reply + ws.onmessage = function(payload) { + try { + const json = extractWsPayload(payload) + debugFn('Hear from server', json) + const { resolverName, type } = json; + switch (type) { + case EMIT_REPLY_TYPE: + let r = ee.$trigger(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), [json]) + debugFn(MESSAGE_PROP_NAME, r) + break; + case ACKNOWLEDGE_REPLY_TYPE: + debugFn(RESULT_PROP_NAME, json) + let x = ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [json]) + debugFn('onResult add to event?', x) + break; + case ERROR_TYPE: + // this is handled error and we won't throw it + // we need to extract the error from json + errorTypeHandler(ee, namespace, resolverName, json) + break; + // @TODO there should be an error type instead of roll into the other two types? TBC + default: + // if this happen then we should throw it and halt the operation all together + debugFn('Unhandled event!', json) + errorTypeHandler(ee, namespace, resolverName, json) + // let error = {error: {'message': 'Unhandled event!', type}}; + // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error]) + } + } catch(e) { + errorTypeHandler(ee, namespace, false, e) + } + } + // when the server close the connection + ws.onclose = function() { + debugFn('ws.onclose') + // @TODO what to do with this + // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) + } + // listen to the LOGOUT_EVENT_NAME + ee.$on(LOGOUT_EVENT_NAME, function close() { + try { + debugFn('terminate ws connection') + ws.terminate() + } catch(e) { + debugFn('terminate ws error', e) + } + }) +} diff --git a/packages/ws-client/beta/src/ws/ws.js b/packages/ws-client/beta/src/ws/ws.js new file mode 100644 index 00000000..e3e94089 --- /dev/null +++ b/packages/ws-client/beta/src/ws/ws.js @@ -0,0 +1,16 @@ +// this is all the isormophic-ws is +var ws = null + +if (typeof WebSocket !== 'undefined') { + ws = WebSocket +} else if (typeof MozWebSocket !== 'undefined') { + ws = MozWebSocket +} else if (typeof global !== 'undefined') { + ws = global.WebSocket || global.MozWebSocket +} else if (typeof window !== 'undefined') { + ws = window.WebSocket || window.MozWebSocket +} else if (typeof self !== 'undefined') { + ws = self.WebSocket || self.MozWebSocket +} + +export default ws; diff --git a/packages/ws-client/dist/jsonql-ws-client.js b/packages/ws-client/dist/jsonql-ws-client.js deleted file mode 100644 index 184f3458..00000000 --- a/packages/ws-client/dist/jsonql-ws-client.js +++ /dev/null @@ -1,7866 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('debug')) : - typeof define === 'function' && define.amd ? define(['debug'], factory) : - (global = global || self, global.jsonqlWsClient = factory(global.debug)); -}(this, function (debug$3) { 'use strict'; - - debug$3 = debug$3 && debug$3.hasOwnProperty('default') ? debug$3['default'] : debug$3; - - // this should work on browser as well as node - // import io from 'socket.io-cilent' - - /** - * Create a normal client - * @param {object} io socket io instance - * @param {string} url end point - * @param {object} [options={}] configuration - * @return {object} nsp instance - */ - function socketIoClient(io, url, options) { - if ( options === void 0 ) options = {}; - - return io.connect(url, options) - } - - // the core stuff to id if it's calling with jsonql - var DATA_KEY = 'data'; - var ERROR_KEY = 'error'; - - var JSONQL_PATH = 'jsonql'; - var DEFAULT_TYPE = 'any'; - - // @TODO remove this is not in use - // export const CLIENT_CONFIG_FILE = '.clients.json'; - // export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; - // type of resolvers - var QUERY_NAME = 'query'; - var MUTATION_NAME = 'mutation'; - var SOCKET_NAME = 'socket'; - var QUERY_ARG_NAME = 'args'; - // for contract-cli - var KEY_WORD = 'continue'; - - var TYPE_KEY = 'type'; - var OPTIONAL_KEY = 'optional'; - var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word - var ARGS_KEY = 'args'; - var CHECKER_KEY = 'checker'; - var ALIAS_KEY = 'alias'; - var LOGIN_NAME = 'login'; - var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later - var LOGOUT_NAME = 'logout'; - - var OR_SEPERATOR = '|'; - - var STRING_TYPE = 'string'; - var BOOLEAN_TYPE = 'boolean'; - var ARRAY_TYPE = 'array'; - var OBJECT_TYPE = 'object'; - - var NUMBER_TYPE = 'number'; - var ARRAY_TYPE_LFT = 'array.<'; - var ARRAY_TYPE_RGT = '>'; - - var NO_ERROR_MSG = 'No message'; - var NO_STATUS_CODE = -1; - var LOGIN_EVENT_NAME = '__login__'; - var LOGOUT_EVENT_NAME = '__logout__'; - - // for ws servers - var WS_REPLY_TYPE = '__reply__'; - var WS_EVT_NAME = '__event__'; - var WS_DATA_NAME = '__data__'; - var EMIT_REPLY_TYPE = 'emit'; - var ACKNOWLEDGE_REPLY_TYPE = 'acknowledge'; - var ERROR_TYPE = 'error'; - - var JS_WS_SOCKET_IO_NAME = 'socket.io'; - var JS_WS_NAME = 'ws'; - - // for ws client - var MESSAGE_PROP_NAME = 'onMessage'; - var RESULT_PROP_NAME = 'onResult'; - var ERROR_PROP_NAME = 'onError'; - var READY_PROP_NAME = 'onReady'; - var SEND_MSG_PROP_NAME = 'send'; - // this is the default time to wait for reply if exceed this then we - // trigger an error --> 5 seconds - var DEFAULT_WS_WAIT_TIME = 5000; - var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; - var HSA_ALGO = 'HS256'; - var TOKEN_PARAM_NAME = 'token'; - - // handshake login - - /** - * Create a async version to match up the rest of the api - * @param {object} io socket io instance - * @param {string} url end point - * @param {object} [options={}] configuration - * @return {object} Promise resolve to nsp instance - */ - function socketIoClientAsync() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return Promise.resolve( - Reflect.apply(socketIoClient, null, args) - ) - } - - /** - * Login during handshake - * @param {object} io the new socket.io instance - * @param {string} token to send - * @param {object} [options = {}] extra options - * @return {object} the io object itself - */ - function socketIoHandshakeLogin(io, url, token, options) { - if ( options === void 0 ) options = {}; - - var wait = options.timeout || DEFAULT_WS_WAIT_TIME; - var config = Object.assign({}, options, { - query: [TOKEN_PARAM_NAME, token].join('=') - }); - var timer; - var nsp = socketIoClient(io, url, config); - return new Promise(function (resolver, rejecter) { - timer = setTimeout(function () { - rejecter(); - }, wait); - nsp.on('connect', function () { - console.info('socketIoHandshakeLogin connected'); - resolver(nsp); - clearTimeout(timer); - }); - }) - } - - /** - * This is a custom error to throw when server throw a 406 - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 406; - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error'; - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; - }(Error)); - - /** - * This is a custom error to throw when server throw a 500 - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error'; - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; - }(Error)); - - /** - * This is a custom error to throw when pass credential but fail - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; - }(Error)); - - /** - * This is a custom error when not supply the credential and try to get contract - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError'; - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; - }(Error)); - - /** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError'; - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; - }(Error)); - - /** - * This is a custom error to throw when could not find the resolver - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 404; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; - }(Error)); - - // this get throw from within the checkOptions when run through the enum failed - var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError'; - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; - }(Error)); - - // this will throw from inside the checkOptions - var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError'; - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; - }(Error)); - - // allow supply a custom checker function - // if that failed then we throw this error - var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError'; - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; - }(Error)); - - // custom validation error class - // when validaton failed - var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; - }(Error)); - - /** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ - var JsonqlError = /*@__PURE__*/(function (Error) { - function JsonqlError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlError); - } - } - - if ( Error ) JsonqlError.__proto__ = Error; - JsonqlError.prototype = Object.create( Error && Error.prototype ); - JsonqlError.prototype.constructor = JsonqlError; - - var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlError'; - }; - - staticAccessors.statusCode.get = function () { - return NO_STATUS_CODE; - }; - - Object.defineProperties( JsonqlError, staticAccessors ); - - return JsonqlError; - }(Error)); - - // this is from an example from Koa team to use for internal middleware ctx.throw - // but after the test the res.body part is unable to extract the required data - // I keep this one here for future reference - - var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError'; - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; - }(Error)); - - /** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ - function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e); - } - var msg = e.message || NO_ERROR_MSG; - var detail = e.detail || e; - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail); - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail); - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail); - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail); - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail); - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail); - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail); - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail); - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail); - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail); - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail); - default: - throw new JsonqlError(msg, detail); - } - } - - // import { isString } from 'jsonql-params-validator'; - /** - * The core method of the socketJwt client side - * @param {object} socket the socket.io connected instance - * @param {string} token for validation - * @param {function} onAuthenitcated callback when authenticated - * @param {function} onUnauthorized callback when authorized - * @return {void} - */ - var socketIoLoginAction = function (socket, token, onAuthenticated, onUnauthorized) { - socket - .emit('authenticate', { token: token }) - .on('authenticated', onAuthenticated) - .on('unauthorized', onUnauthorized); - }; - - /** - * completely rethink about how the browser version should be! - * - */ - function socketIoRoundtripLogin(io, url, token, options) { - - var socket = socketIoClient(io, url); - return new Promise(function (resolver, rejecter) { - socketIoLoginAction(socket, token, function () { return resolver(socket); } , rejecter); - }) - } - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Built-in value references. */ - var Symbol = root.Symbol; - - /** Used for built-in method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - - /** Built-in value references. */ - var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$1 = Object.prototype; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString$1 = objectProto$1.toString; - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString$1.call(value); - } - - /** `Object#toString` result references. */ - var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - - /** Built-in value references. */ - var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined; - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag$1 && symToStringTag$1 in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** `Object#toString` result references. */ - var symbolTag = '[object Symbol]'; - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ - function identity(value) { - return value; - } - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** Used for built-in method references. */ - var funcProto = Function.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used for built-in method references. */ - var funcProto$1 = Function.prototype, - objectProto$2 = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$1 = funcProto$1.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /* Built-in method references that are verified to be native. */ - var WeakMap$1 = getNative(root, 'WeakMap'); - - /** Built-in value references. */ - var objectCreate = Object.create; - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeNow = Date.now; - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** Used for built-in method references. */ - var objectProto$3 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$2.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER$1 = 9007199254740991; - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; - } - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** Used for built-in method references. */ - var objectProto$4 = Object.prototype; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4; - - return value === proto; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]'; - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** Used for built-in method references. */ - var objectProto$5 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$3 = objectProto$5.hasOwnProperty; - - /** Built-in value references. */ - var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$3.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** `Object#toString` result references. */ - var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag$1 = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** Detect free variable `exports`. */ - var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports$1 && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** Used for built-in method references. */ - var objectProto$6 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$4.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeKeys = overArg(Object.keys, Object); - - /** Used for built-in method references. */ - var objectProto$7 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$5.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** Used for built-in method references. */ - var objectProto$8 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$6.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /* Built-in method references that are verified to be native. */ - var nativeCreate = getNative(Object, 'create'); - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used for built-in method references. */ - var objectProto$9 = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$7.call(data, key) ? data[key] : undefined; - } - - /** Used for built-in method references. */ - var objectProto$a = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$8 = objectProto$a.hasOwnProperty; - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$8.call(data, key); - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; - } - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype; - - /** Built-in value references. */ - var splice = arrayProto.splice; - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /* Built-in method references that are verified to be native. */ - var Map$1 = getNative(root, 'Map'); - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** Error message constants. */ - var FUNC_ERROR_TEXT = 'Expected a function'; - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** Used as references for various `Number` constants. */ - var INFINITY$1 = 1 / 0; - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** Built-in value references. */ - var getPrototype = overArg(Object.getPrototypeOf, Object); - - /** `Object#toString` result references. */ - var objectTag$1 = '[object Object]'; - - /** Used for built-in method references. */ - var funcProto$2 = Function.prototype, - objectProto$b = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString$2 = funcProto$2.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty$9 = objectProto$b.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString$2.call(Object); - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag$1) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$9.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString$2.call(Ctor) == objectCtorString; - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; - - /** Used to compose unicode capture groups. */ - var rsZWJ = '\\u200d'; - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - - /** Used to compose unicode character classes. */ - var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; - - /** Used to compose unicode capture groups. */ - var rsAstral = '[' + rsAstralRange$1 + ']', - rsCombo = '[' + rsComboRange$1 + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange$1 + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ$1 = '\\u200d'; - - /** Used to compose unicode regexes. */ - var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange$1 + ']?', - rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** Detect free variable `exports`. */ - var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - - /** Built-in value references. */ - var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** Used for built-in method references. */ - var objectProto$c = Object.prototype; - - /** Built-in value references. */ - var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); - }; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'); - - /* Built-in method references that are verified to be native. */ - var Promise$1 = getNative(root, 'Promise'); - - /* Built-in method references that are verified to be native. */ - var Set$1 = getNative(root, 'Set'); - - /** `Object#toString` result references. */ - var mapTag$1 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$1 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - - var dataViewTag$1 = '[object DataView]'; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) || - (Map$1 && getTag(new Map$1) != mapTag$1) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$1) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$1; - case mapCtorString: return mapTag$1; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$1; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; - } - - var getTag$1 = getTag; - - /** Built-in value references. */ - var Uint8Array = root.Uint8Array; - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - - /** `Object#toString` result references. */ - var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$2 = '[object Map]', - numberTag$1 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$2 = '[object Set]', - stringTag$1 = '[object String]', - symbolTag$1 = '[object Symbol]'; - - var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$2 = '[object DataView]'; - - /** Used to convert symbols to primitives and strings. */ - var symbolProto$1 = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$2: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$1: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$1: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$2: - var convert = mapToArray; - - case setTag$2: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$2 = 1; - - /** Used for built-in method references. */ - var objectProto$d = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$a = objectProto$d.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$3 = 1; - - /** `Object#toString` result references. */ - var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto$e = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty$b = objectProto$e.hasOwnProperty; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$b.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); - } - - /** `Object#toString` result references. */ - var stringTag$2 = '[object String]'; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag$2); - } - - /** `Object#toString` result references. */ - var boolTag$2 = '[object Boolean]'; - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag$2); - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** `Object#toString` result references. */ - var numberTag$2 = '[object Number]'; - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag$2); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** Error message constants. */ - var FUNC_ERROR_TEXT$1 = 'Expected a function'; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g; - - /** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ - function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); - } - - /** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - - function notEmpty (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; - } - - // validator numbers - /** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a check if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ - var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN( parseFloat(value) ) - }; - - // validate string type - /** - * @param {string} value expected value - * @return {boolean} true if OK - */ - var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false; - }; - - // check for boolean - /** - * @param {boolean} value expected - * @return {boolean} true if OK - */ - var checkIsBoolean = function(value) { - return isBoolean(value); - }; - - // validate any thing only check if there is something - /** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ - var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (!isUndefined(value) && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && !isNull(value))) { - return true; - } - } - return false; - }; - - // Good practice rule - No magic number - - var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; - var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; - var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; - // @TODO the jsdoc return array. and we should also allow array syntax - var DEFAULT_TYPE$1 = DEFAULT_TYPE; - var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; - var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - - var TYPE_KEY$1 = TYPE_KEY; - var OPTIONAL_KEY$1 = OPTIONAL_KEY; - var ENUM_KEY$1 = ENUM_KEY; - var ARGS_KEY$1 = ARGS_KEY; - var CHECKER_KEY$1 = CHECKER_KEY; - var ALIAS_KEY$1 = ALIAS_KEY; - - var ARRAY_TYPE$1 = ARRAY_TYPE; - var OBJECT_TYPE$1 = OBJECT_TYPE; - var STRING_TYPE$1 = STRING_TYPE; - var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; - var NUMBER_TYPE$1 = NUMBER_TYPE; - var KEY_WORD$1 = KEY_WORD; - var OR_SEPERATOR$1 = OR_SEPERATOR; - - // not actually in use - // export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - - // primitive types - - /** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ - var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } - }; - - // validate array type - - /** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ - var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false; - }; - - /** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ - var isArrayLike$1 = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] - } - return false; - }; - - /** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ - var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length; - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; - }; - - // validate object type - /** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ - var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (!isUndefined(_value)) { - if ((tmp = isArrayLike$1(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true; - }).length) - }).length; - } - } - return false; - }; - - /** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ - var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return checkIsObject.apply(null, _args) - }; - - // move the index.js code here that make more sense to find where things are - - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:validator') - // also export this for use in other places - - /** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ - var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (notEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false; - }; - - /** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ - var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike$1(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } - }; - - /** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ - var getOptionalValue = function(arg, param) { - if (!isUndefined(arg)) { - return arg; - } - return (param.optional === true && !isUndefined(param.defaultvalue) ? param.defaultvalue : null) - }; - - /** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ - var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return []; - } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }); - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }); - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }); - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length && params.length === 1: - // this happens when we have those array. type - var tmp, _type = [ DEFAULT_TYPE$1 ]; - // we only looking at the first one, this might be a @BUG! - if ((tmp = isArrayLike$1(params[0].type[0])) !== false) { - _type = tmp; - } - // if not then we fall back to the following - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] || { type: _type, name: '_' } - } - ); }); - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) - } - }; - - // what we want is after the validaton we also get the normalized result - // which is with the optional property if the argument didn't provide it - /** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ - var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - - /** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ - var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - if (p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) - }; - - /** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ - var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) - }; - - /** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ - var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; - }; - - /** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ - var checkKeyInObject = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) - }; - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:prepare') - - // just not to make my head hurt - var isEmpty = function (value) { return !notEmpty(value); }; - - /** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ - function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) - } - - /** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ - function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return checkKeyInObject(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !checkKeyInObject(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } - } - - /** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ - function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - isUndefined(config[key]) || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) - } - - /** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] - } - - // breaking the whole thing up to see what cause the multiple calls issue - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:validation') - - /** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ - var toArray = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - - /** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ - var inArray = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length - ); }; - - /** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ - function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) - } - - /** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ - var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray(enumv, value) - } - return true; - }; - - /** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ - var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false; - } catch (e) { - return false; - } - }; - - /** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ - function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // debugFn('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } - } - - /** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ - function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) - } - - // this is port back from the client to share across all projects - - // import debug from 'debug' - // const debugFn = debug('jsonql-params-validator:check-options-async') - - /** - * Quick transform - * @param {object} config that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ - var configToArgs = function (config, appProps) { - return Promise.resolve( - prepareArgsForValidation(config, appProps) - ) - }; - - /** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ - function checkOptionsAsync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return configToArgs(config, appProps) - .then(function (args1) { - // debugFn('args', args1) - return runValidation(args1, cb) - }) - // next if every thing good then pass to final merging - .then(function (args2) { return merge({}, args2, constProps); }) - } - - // create function to construct the config entry so we don't need to keep building object - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:construct-config'); - /** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ - function constructConfigFn(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base; - } - - // export also create wrapper methods - - // import debug from 'debug'; - // const debugFn = debug('jsonql-params-validator:options:index'); - - /** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ - var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfigFn.apply(null, [value, type, o, e, c, a]) - }; - - /** - * We recreate the method here to avoid the circlar import - * @param {object} config user supply configuration - * @param {object} appProps mutation options - * @param {object} [constantProps={}] optional: immutation options - * @return {object} all checked configuration - */ - var checkConfigAsync = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps= {}; - - return checkOptionsAsync(config, appProps, constantProps, validateSync) - } - }; - - // since this need to use everywhere might as well include in the validator - - function checkIsContract(contract) { - return checkIsObject(contract) - && ( - checkKeyInObject(contract, QUERY_NAME) - || checkKeyInObject(contract, MUTATION_NAME) - || checkKeyInObject(contract, SOCKET_NAME) - ) - } - - // craete several helper function to construct / extract the payload - - /** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ - function getNameFromPayload(payload) { - return Object.keys(payload)[0] - } - - /** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ - function createQuery(resolverName, args, jsonp) { - var obj; - - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - if (checkIsString(resolverName) && checkIsArray(args)) { - var payload = {}; - payload[QUERY_ARG_NAME] = args; - if (jsonp === true) { - return payload; - } - return ( obj = {}, obj[resolverName] = payload, obj ) - } - throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) - } - - // string version of the above - function createQueryStr(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - return JSON.stringify(createQuery(resolverName, args, jsonp)) - } - - // export - var isString$1 = checkIsString; - var isArray$1 = checkIsArray; - var validateSync$1 = validateSync; - var validateAsync$1 = validateAsync; - - var createConfig$1 = createConfig; - - var checkConfigAsync$1 = checkConfigAsync(validateSync); - - var isKeyInObject = checkKeyInObject; - - var isContract = checkIsContract; - var createQueryStr$1 = createQueryStr; - var getNameFromPayload$1 = getNameFromPayload; - - // This is ported back from ws-server and it will get use in the server / client side - - function extractSocketPart(contract) { - if (isKeyInObject(contract, 'socket')) { - return contract.socket; - } - return contract; - } - - /** - * @BUG we should check the socket part instead of expect the downstream to read the menu! - * We only need this when the enableAuth is true otherwise there is only one namespace - * @param {object} contract the socket part of the contract file - * @return {object} 1. remap the contract using the namespace --> resolvers - * 2. the size of the object (1 all private, 2 mixed public with private) - * 3. which namespace is public - */ - function groupByNamespace(contract) { - var socket = extractSocketPart(contract); - - var nspSet = {}; - var size = 0; - var publicNamespace; - for (var resolverName in socket) { - var params = socket[resolverName]; - var namespace = params.namespace; - if (namespace) { - if (!nspSet[namespace]) { - ++size; - nspSet[namespace] = {}; - } - nspSet[namespace][resolverName] = params; - if (!publicNamespace) { - if (params.public) { - publicNamespace = namespace; - } - } - } - } - return { size: size, nspSet: nspSet, publicNamespace: publicNamespace } - } - - // This is ported back from ws-client - // the idea if from https://decembersoft.com/posts/promises-in-serial-with-array-reduce/ - /** - * previously we already make sure the order of the namespaces - * and attach the auth client to it - * @param {array} promises array of unresolved promises - * @return {object} promise resolved with the array of promises resolved results - */ - function chainPromises(promises) { - return promises.reduce(function (promiseChain, currentTask) { return ( - promiseChain.then(function (chainResults) { return ( - currentTask.then(function (currentResult) { return ( - chainResults.concat( [currentResult]) - ); }) - ); }) - ); }, Promise.resolve([])) - } - - /** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - function InvalidCharacterError(message) { - this.message = message; - } - - InvalidCharacterError.prototype = new Error(); - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - function polyfill (input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - } - - - var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; - - function InvalidTokenError(message) { - this.message = message; - } - - InvalidTokenError.prototype = new Error(); - InvalidTokenError.prototype.name = 'InvalidTokenError'; - - var obj, obj$1, obj$2, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - - var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj = {}, obj[ALIAS_KEY] = 'exp', obj[OPTIONAL_KEY] = true, obj )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1 = {}, obj$1[ALIAS_KEY] = 'nbf', obj$1[OPTIONAL_KEY] = true, obj$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'iss', obj$2[OPTIONAL_KEY] = true, obj$2 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) - }; - - // ws client using native WebSocket - - function getWS() { - switch(true) { - case (typeof WebSocket !== 'undefined'): - return WebSocket; - case (typeof MozWebSocket !== 'undefined'): - return MozWebSocket; - // case (typeof global !== 'undefined'): - // return global.WebSocket || global.MozWebSocket; - case (typeof window !== 'undefined'): - return window.WebSocket || window.MozWebSocket; - // case (typeof self !== 'undefined'): - // return self.WebSocket || self.MozWebSocket; - default: - throw new JsonqlValidationError('WebSocket is NOT SUPPORTED!') - } - } - - var WS = getWS(); - /** - * Create a client with auth token - * @param {string} url start with ws:// @TODO check this? - * @param {string} token the jwt token - * @return {object} ws instance - */ - function wsAuthClient(url, token) { - return wsClient((url + "?" + TOKEN_PARAM_NAME + "=" + token)) - } - - /** - * Also create a normal client this is for down stream to able to use in node and browser - * @NOTE CAN NOT pass an option if I do then the brower throw error - * @param {string} url end point - * @return {object} ws instance - */ - function wsClient(url) { - return new WS(url) - } - - // constants - - var SOCKET_IO = JS_WS_SOCKET_IO_NAME; - var WS$1 = JS_WS_NAME; - - var AVAILABLE_SERVERS = [SOCKET_IO, WS$1]; - - var SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'; - - var MISSING_PROP_ERR = 'Missing property in contract!'; - - var EMIT_EVT = EMIT_REPLY_TYPE; - - var UNKNOWN_RESULT = 'UKNNOWN RESULT!'; - - var MY_NAMESPACE = 'myNamespace'; - - /** - * Try to normalize it to use between browser and node - * @param {string} name for the debug output - * @return {function} debug - */ - var getDebug = function (name) { - if (debug$3) { - return debug$3('jsonql-ws-client').extend(name) - } - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - console.info.apply(null, [name].concat(args)); - } - }; - try { - if (window && window.localStorage) { - localStorage.setItem('DEBUG', 'jsonql-ws-client*'); - } - } catch(e) {} - - // generate the web socket connect client for browser - var debug = getDebug('client-generator'); - - /** - * create the web socket client - * @param {object} payload passing - * @return {object} just mutate it then pass it on - */ - function clientGenerator(ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - switch (opts.serverType) { - case SOCKET_IO: - opts.nspClient = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - Reflect.apply(socketIoClientAsync, null, [io ].concat( args)) - ); - }; - if (isString$1(opts.useJwt)) { - opts.nspAuthClient = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - Reflect.apply(socketIoRoundtripLogin, null, [io ].concat( args)) - ); - }; - } else { - opts.nspAuthClient = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return ( - Reflect.apply(socketIoHandshakeLogin, null, [io ].concat( args)) - ); - }; - } - break; - case WS$1: - opts.nspClient = wsClient; - opts.nspAuthClient = wsAuthClient; - break; - default: - throw new JsonqlError(("Unknown serverType: " + (opts.serverType))) - } - return {opts: opts, nspMap: nspMap, ee: ee} - } - - // since both the ws and io version are - var debugFn = getDebug('create-nsp-client'); - /** - * wrapper method to create a nsp without login - * @param {string|boolean} namespace namespace url could be false - * @param {object} opts configuration - * @return {object} ws client instance - */ - var nspClient = function (namespace, opts) { - var wssPath = opts.wssPath; - var wsOptions = opts.wsOptions; - var hostname = opts.hostname; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - return opts.nspClient(url, wsOptions) - }; - - /** - * wrapper method to create a nsp with token auth - * @param {string} namespace namespace url - * @param {object} opts configuration - * @return {object} ws client instance - */ - var nspAuthClient = function (namespace, opts) { - var wssPath = opts.wssPath; - var token = opts.token; - var wsOptions = opts.wsOptions; - var hostname = opts.hostname; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - return opts.nspAuthClient(url, token, wsOptions) - }; - - /** - * Got to make sure the connection order otherwise - * it will hang - * @param {object} nspSet contract - * @param {string} publicNamespace like the name said - * @return {array} namespaces in order - */ - function getNamespaceInOrder(nspSet, publicNamespace) { - var names = []; // need to make sure the order! - for (var namespace in nspSet) { - if (namespace === publicNamespace) { - names[1] = namespace; - } else { - names[0] = namespace; - } - } - return names; - } - - var obj$9, obj$1$1; - var debug$1 = getDebug('check-options'); - - var fixWss = function (url, serverType) { - // ws only allow ws:// path - if (serverType===WS$1) { - return url.replace('http://', 'ws://') - } - return url; - }; - - var getHostName = function () { return ( - [window.location.protocol, window.location.host].join('//') - ); }; - - var constProps = { - // this will be the switcher! - nspClient: null, - nspAuthClient: null, - // contructed path - wssPath: '' - }; - - var defaultOptions = { - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // we will use this for determine the socket.io client type as well - useJwt: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE]), - hostname: createConfig$1(false, [STRING_TYPE]), - namespace: createConfig$1(JSONQL_PATH, [STRING_TYPE]), - wsOptions: createConfig$1({transports: ['websocket'], 'force new connection' : true}, [OBJECT_TYPE]), - serverType: createConfig$1(SOCKET_IO, [STRING_TYPE], ( obj$9 = {}, obj$9[ENUM_KEY] = AVAILABLE_SERVERS, obj$9 )), - // we require the contract already generated and pass here - contract: createConfig$1({}, [OBJECT_TYPE], ( obj$1$1 = {}, obj$1$1[CHECKER_KEY] = isContract, obj$1$1 )), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - token: createConfig$1(false, [STRING_TYPE]) - }; - // export - function checkOptions(config) { - return checkConfigAsync$1(config, defaultOptions, constProps) - .then(function (opts) { - if (!opts.hostname) { - opts.hostname = getHostName(); - } - // @TODO the contract now will supply the namespace information - // and we need to use that to group the namespace call - opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType); - - debug$1('opts', opts); - return opts; - }) - } - - var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); - var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - - /** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ - function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) - } - - // making all the functionality on it's own - // import { WatchClass } from './watch' - - var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ - }; - - var prototypeAccessors = { $suspend: { configurable: true },$queues: { configurable: true } }; - - /** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ - prototypeAccessors.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } - }; - - /** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ - SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; - }; - - /** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ - prototypeAccessors.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] - }; - - /** - * Release the queue - * @return {int} size if any - */ - SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); - } - }; - - Object.defineProperties( SuspendClass.prototype, prototypeAccessors ); - - // break up the main file because its getting way too long - - var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - } - - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") - } - }); - return true; - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; - } - } - throw new Error("callback required to be function type!") - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - if (store.has(evt)) { - var content = store.get(evt); - this.logger('(takeFromStore)', ("has " + evt), content); - store.delete(evt); - return content; - } - return false; - } - throw new Error((storeName + " is not supported!")) - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet; - if (store.has(evt)) { - this.logger('(addToStore)', (evt + " existed")); - fnSet = store.get(evt); - } else { - this.logger('(addToStore)', ("create new Set for " + evt)); - // this is new - fnSet = new Set(); - } - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger('(addToStore)', "insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; - } - return false; - }).length; - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true; - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - this.logger('(checkTypeInLazyStore)', store); - if (store) { - return !!Array - .from(store) - .filter(function (l) { - var t = l[2]; - return t !== type; - }).length - } - return false; - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - return size; - } - return false; - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - return size; - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; - - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - - return NbEventServiceBase; - }(SuspendClass)); - - // The top level - // export - var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - NbStoreService.call(this, config); - } - - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger('($on)', (evt + " callback is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - - return this.addToNormalStore(evt, type, callback, context) - } - this.logger('($on)', (evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - return size; - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, type, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'only'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($only)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($only)', (evt + " found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.run(callback, payload, context || ctx); - }); - } - return added; - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD adeed in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'onlyOnce'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($onlyOnce)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added; - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = 'on'; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var type$1 = ref[3]; - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var args = [evt, params]; - args.push(context, type); - return Reflect.apply(this.$trigger, this, args) - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - store.delete(evt); - } - }); - return found; - }; - - /** - * return all the listener from the event - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; - }) - } - return false; - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; - }(NbEventServiceBase)); - - // default - - // create a clone version so we know which one we actually is using - var JsonqlWsEvt = /*@__PURE__*/(function (NBEventService) { - function JsonqlWsEvt() { - NBEventService.call(this, {logger: getDebug('nb-event-service')}); - } - - if ( NBEventService ) JsonqlWsEvt.__proto__ = NBEventService; - JsonqlWsEvt.prototype = Object.create( NBEventService && NBEventService.prototype ); - JsonqlWsEvt.prototype.constructor = JsonqlWsEvt; - - var prototypeAccessors = { name: { configurable: true } }; - - prototypeAccessors.name.get = function () { - return 'jsonql-ws-client' - }; - - Object.defineProperties( JsonqlWsEvt.prototype, prototypeAccessors ); - - return JsonqlWsEvt; - }(EventService)); - - // mapping the resolver to their respective nsp - var debug$2 = getDebug('process-contract'); - - /** - * Just make sure the object contain what we are looking for - * @param {object} opts configuration from checkOptions - * @return {object} the target content - */ - var getResolverList = function (contract) { - if (contract) { - var socket = contract.socket; - if (socket) { - return socket; - } - } - throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR) - }; - - /** - * process the contract first - * @param {object} opts configuration - * @return {object} sorted list - */ - function processContract(opts) { - var obj; - - var contract = opts.contract; - var enableAuth = opts.enableAuth; - if (enableAuth) { - return groupByNamespace(contract) - } - return { - nspSet: ( obj = {}, obj[JSONQL_PATH] = getResolverList(contract), obj ), - publicNamespace: JSONQL_PATH, - size: 1 // this prop is pretty meaningless now - } - } - - // export the util methods - - var toArray$1 = function (arg) { return isArray$1(arg) ? arg : [arg]; }; - - /** - * very simple tool to create the event name - * @param {string} [...args] spread - * @return {string} join by _ - */ - var createEvt = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.join('_'); - }; - - /** - * Unbind the event - * @param {object} ee EventEmitter - * @param {string} namespace - * @return {void} - */ - var clearMainEmitEvt = function (ee, namespace) { - var nsps = isArray$1(namespace) ? namespace : [namespace]; - nsps.forEach(function (n) { - ee.$off(createEvt(n, EMIT_EVT)); - }); - }; - - /** - * @param {*} args arguments to send - *@return {object} formatted payload - */ - var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) - ); - }; - - /** - * @param {object} nsps namespace as key - * @param {string} type of server - */ - var disconnect = function (nsps, type) { - if ( type === void 0 ) type = JS_WS_SOCKET_IO_NAME; - - try { - var method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate'; - for (var namespace in nsps) { - var nsp = nsps[namespace]; - if (nsp && nsp[method]) { - Reflect.apply(nsp[method], null, []); - } - } - } catch(e) { - // socket.io throw a this.destroy of undefined? - console.error('disconnect', e); - } - }; - - /** - * trigger errors on all the namespace onError handler - * @param {object} ee Event Emitter - * @param {array} namespaces nsps string - * @param {string} message optional - * @return {void} - */ - function triggerNamespacesOnError(ee, namespaces, message) { - namespaces.forEach( function (namespace) { - ee.$call(createEvt(namespace, ERROR_PROP_NAME), [{ message: message, namespace: namespace }]); - }); - } - - // @TODO port what is in the ws-main-handler - var debugFn$1 = getDebug('client-event-handler'); - - /** - * A fake ee handler - * @param {string} namespace nsp - * @param {object} ee EventEmitter - * @return {void} - */ - var notLoginWsHandler = function (namespace, ee) { - ee.$only( - createEvt(namespace, EMIT_EVT), - function(resolverName, args) { - debugFn$1('noLoginHandler hijack the ws call', namespace, resolverName, args); - var error = { - message: NOT_LOGIN_ERR_MSG - }; - // It should just throw error here and should not call the result - // because that's channel for handling normal event not the fake one - ee.$call(createEvt(namespace, resolverName, ERROR_PROP_NAME), [error]); - // also trigger the result handler, but wrap inside the error key - ee.$call(createEvt(namespace, resolverName, RESULT_PROP_NAME), [{ error: error }]); - } - ); - }; - - /** - * centralize all the comm in one place - * @param {object} opts configuration - * @param {array} namespaces namespace(s) - * @param {object} ee Event Emitter instance - * @param {function} bindWsHandler binding the ee to ws - * @param {array} namespaces array of namespace available - * @param {object} nsps namespaced nsp - * @return {void} nothing - */ - function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) { - // loop - // @BUG for io this has to be in order the one with auth need to get call first - // The order of login is very import we need to run a waterfall here to make sure - // one is execute then the other - namespaces.forEach(function (namespace) { - if (nsps[namespace]) { - debugFn$1('call bindWsHandler', namespace); - var args = [namespace, nsps[namespace], ee]; - if (opts.serverType === SOCKET_IO) { - var nspSet = nspMap.nspSet; - args.push(nspSet[namespace]); - args.push(opts); - } - Reflect.apply(bindWsHandler, null, args); - } else { - // a dummy placeholder - notLoginWsHandler(namespace, ee); - } - }); - // this will be available regardless enableAuth - // because the server can log the client out - ee.$on(LOGOUT_EVENT_NAME, function() { - debugFn$1('LOGOUT_EVENT_NAME'); - // disconnect(nsps, opts.serverType) - // we need to issue error to all the namespace onError handler - triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME); - // rebind all of the handler to the fake one - namespaces.forEach( function (namespace) { - clearMainEmitEvt(ee, namespace); - // clear out the nsp - nsps[namespace] = false; - // add a NOT LOGIN error if call - notLoginWsHandler(namespace, ee); - }); - }); - } - - // take the ws reply data for use - var debugFn$2 = getDebug('extract-ws-payload'); - - var keys$1 = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]; - - /** - * @param {object} payload should be string when reply but could be transformed - * @return {boolean} true is OK - */ - var isWsReply = function (payload) { - var data = payload.data; - if (data) { - var result = keys$1.filter(function (key) { return isKeyInObject(data, key); }); - return (result.length === keys$1.length) ? data : false; - } - return false; - }; - - /** - * @param {object} payload This is the entire ws Event Object - * @return {object} false on failed - */ - var extractWsPayload = function (payload) { - var data = payload.data; - var json = isString$1(data) ? JSON.parse(data) : data; - // debugFn('extractWsPayload', json) - var fdata; - if ((fdata = isWsReply(json)) !== false) { - return { - resolverName: fdata[WS_EVT_NAME], - data: fdata[WS_DATA_NAME], - type: fdata[WS_REPLY_TYPE] - }; - } - throw new JsonqlError('payload can not be decoded', payload) - }; - - // the WebSocket main handler - var debugFn$3 = getDebug('ws-main-handler'); - - /** - * under extremely circumstances we might not even have a resolverName, then - * we issue a global error for the developer to catch it - * @param {object} ee event emitter - * @param {string} namespace nsp - * @param {string} resolverName resolver - * @param {object} json decoded payload or error object - */ - var errorTypeHandler = function (ee, namespace, resolverName, json) { - var evt = [namespace]; - if (resolverName) { - debugFn$3(("a global error on " + namespace)); - evt.push(resolverName); - } - evt.push(ERROR_PROP_NAME); - var evtName = Reflect.apply(createEvt, null, evt); - // test if there is a data field - var payload = json.data || json; - ee.$trigger(evtName, [payload]); - }; - - /** - * Binding the even to socket normally - * @param {string} namespace - * @param {object} ws the nsp - * @param {object} ee EventEmitter - * @return {object} promise resolve after the onopen event - */ - function wsMainHandlerAction(namespace, ws, ee) { - // send - ws.onopen = function() { - // we just call the onReady - ee.$call(READY_PROP_NAME, namespace); - // add listener - ee.$only( - createEvt(namespace, EMIT_EVT), - function(resolverName, args) { - debugFn$3('calling server', resolverName, args); - ws.send( - createQueryStr$1(resolverName, args) - ); - } - ); - }; - - // reply - ws.onmessage = function(payload) { - try { - var json = extractWsPayload(payload); - debugFn$3('Hear from server', json); - var resolverName = json.resolverName; - var type = json.type; - switch (type) { - case EMIT_REPLY_TYPE: - var r = ee.$trigger(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), [json]); - debugFn$3(MESSAGE_PROP_NAME, r); - break; - case ACKNOWLEDGE_REPLY_TYPE: - debugFn$3(RESULT_PROP_NAME, json); - var x = ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [json]); - debugFn$3('onResult add to event?', x); - break; - case ERROR_TYPE: - // this is handled error and we won't throw it - // we need to extract the error from json - errorTypeHandler(ee, namespace, resolverName, json); - break; - // @TODO there should be an error type instead of roll into the other two types? TBC - default: - // if this happen then we should throw it and halt the operation all together - debugFn$3('Unhandled event!', json); - errorTypeHandler(ee, namespace, resolverName, json); - // let error = {error: {'message': 'Unhandled event!', type}}; - // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error]) - } - } catch(e) { - errorTypeHandler(ee, namespace, false, e); - } - }; - // when the server close the connection - ws.onclose = function() { - debugFn$3('ws.onclose'); - // @TODO what to do with this - // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) - }; - // listen to the LOGOUT_EVENT_NAME - ee.$on(LOGOUT_EVENT_NAME, function close() { - try { - debugFn$3('terminate ws connection'); - ws.terminate(); - } catch(e) { - debugFn$3('terminate ws error', e); - } - }); - } - - // make this another standalone module - var debugFn$4 = getDebug('ws-create-client'); - - /** - * Because the nsps can be throw away so it doesn't matter the scope - * this will get reuse again - * @param {object} opts configuration - * @param {object} nspMap from contract - * @param {string|null} token whether we have the token at run time - * @return {object} nsps namespace with namespace as key - */ - var createNsps = function(opts, nspMap, token) { - var nspSet = nspMap.nspSet; - var publicNamespace = nspMap.publicNamespace; - var login = false; - var namespaces = []; - var nsps = {}; - // first we need to binding all the events handler - if (opts.enableAuth && opts.useJwt) { - login = true; // just saying we need to listen to login event - namespaces = getNamespaceInOrder(nspSet, publicNamespace); - nsps = namespaces.map(function (namespace, i) { - var obj, obj$1, obj$2; - - if (i === 0) { - if (token) { - opts.token = token; - return ( obj = {}, obj[namespace] = nspAuthClient(namespace, opts), obj ) - } - return ( obj$1 = {}, obj$1[namespace] = false, obj$1 ) - } - return ( obj$2 = {}, obj$2[namespace] = nspClient(namespace, opts), obj$2 ) - }).reduce(function (first, next) { return Object.assign(first, next); }, {}); - } else { - var namespace = getNameFromPayload$1(nspSet); - namespaces.push(namespace); - // standard without login - // the stock version should not have a namespace - nsps[namespace] = nspClient(false, opts); - } - // return - return { nsps: nsps, namespaces: namespaces, login: login } - }; - - /** - * create a ws client - * @param {object} opts configuration - * @param {object} nspMap namespace with resolvers - * @param {object} ee EventEmitter to pass through - * @return {object} what comes in what goes out - */ - function createClient(opts, nspMap, ee) { - // arguments that don't change - var args = [opts, nspMap, ee, wsMainHandlerAction]; - // now create the nsps - var ref = createNsps(opts, nspMap, opts.token); - var nsps = ref.nsps; - var namespaces = ref.namespaces; - var login = ref.login; - // binding the listeners - and it will listen to LOGOUT event - // to unbind itself, and the above call will bind it again - Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])); - // setup listener - if (login) { - ee.$only(LOGIN_EVENT_NAME, function(token) { - disconnect(nsps, JS_WS_NAME); - // @TODO should we trigger error on this one? - // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME) - clearMainEmitEvt(ee, namespaces); - debugFn$4('LOGIN_EVENT_NAME', token); - var newNsps = createNsps(opts, nspMap, token); - // rebind it - Reflect.apply( - clientEventHandler, - null, - args.concat([newNsps.namespaces, newNsps.nsps]) - ); - }); - } - // return what input - return { opts: opts, nspMap: nspMap, ee: ee } - } - - // we only need to export one interface from now on - - var debugFn$5 = getDebug('io-main-handler'); - - /** - * @param {object} ee Event Emitter - * @param {string} namespace namespace of this nsp - * @param {string} resolverName resolver to handle this call - * @return {function} capture the result - */ - var resultHandler = function (ee, namespace, resolverName, evt) { - if ( evt === void 0 ) evt = RESULT_PROP_NAME; - - return function (result) { - ee.$trigger(createEvt(namespace, resolverName, evt), [result]); - } - }; - - /** - * @param {object} nspSet resolver list - * @param {object} nsp nsp instance - * @param {object} ee Event Emitter - * @param {string} namespace name of this nsp - * @return {void} - */ - var createResolverListener = function (nspSet, nsp, ee, namespace) { - for (var resolverName in nspSet) { - nsp.on( - resolverName, - resultHandler(ee, namespace, resolverName, MESSAGE_PROP_NAME) - ); - } - }; - - /** - * @param {object} nsp instance - * @param {object} ee Event Emitter - * @param {string} namespace name of this nsp - * @return {void} - */ - var mainEventHandler = function (nsp, ee, namespace) { - ee.$only( - createEvt(namespace, EMIT_EVT), - function resolverEmitHandler(resolverName, args) { - debugFn$5('mainEventHandler', resolverName, args); - nsp.emit( - resolverName, - formatPayload(args), - resultHandler(ee, namespace, resolverName) - ); - } - ); - }; - - /** - * it makes no different at this point if we know its connection establish or not - * We should actually know this before hand before we call here - * @param {string} namespace of this client - * @param {object} socket this is the resolved nsp connection object - * @param {object} ee Event Emitter - * @param {object} nspSet the list of resolvers - * @param {object} opts configuration - */ - function ioMainHandler(namespace, socket, ee, nspSet, opts) { - // the main listener for all the client resolvers - mainEventHandler(socket, ee, namespace); - // it doesn't make much different between inside the connect or not - // loop through to create the listeners - createResolverListener(nspSet, socket, ee, namespace); - //@TODO next we need to add a ERROR handler - // The server side is not implementing a global ERROR call yet - // and the result or message error will be handle individually by their callback - // listen to the server close event - socket.on('disconnect', function disconnect() { - debugFn$5('io.disconnect'); - // TBC what to do with this - // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) - }); - // listen to the logout event - ee.$on(LOGOUT_EVENT_NAME, function logoutHandler() { - try { - debugFn$5('terminate ws connection'); - socket.close(); - } catch(e) { - debugFn$5('terminate ws error', e); - } - }); - // the last one to fire - ee.$trigger(READY_PROP_NAME, namespace); - } - - // this will create the socket.io client - var debugFn$6 = getDebug('io-create-client'); - - // just to make it less ugly - var mapNsps = function (nsps, namespaces) { return nsps - .map(function (nsp, i) { - var obj; - - return (( obj = {}, obj[namespaces[i]] = nsp, obj )); - }) - .reduce(function (last, next) { return Object.assign(last,next); }, {}); }; - - /** - * This one will run the create nsps in sequence and make sure - * the auth one connect before we call the others - * @param {object} opts configuration - * @param {object} nspMap contract map - * @param {string} token validation - * @return {object} promise resolve with namespaces, nsps in same order array - */ - var createAuthNsps = function(opts, nspMap, token, namespaces) { - var publicNamespace = nspMap.publicNamespace; - opts.token = token; - var p1 = function () { return nspAuthClient(namespaces[0], opts); }; - var p2 = function () { return nspClient(namespaces[1], opts); }; - return chainPromises([p1(), p2()]) - .then(function (nsps) { return ({ - nsps: mapNsps(nsps, namespaces), - namespaces: namespaces, - login: false - }); }) - }; - - /** - * Because the nsps can be throw away so it doesn't matter the scope - * this will get reuse again - * @param {object} opts configuration - * @param {object} nspMap from contract - * @param {string|null} token whether we have the token at run time - * @return {object} nsps namespace with namespace as key - */ - var createNsps$1 = function(opts, nspMap, token) { - var nspSet = nspMap.nspSet; - var publicNamespace = nspMap.publicNamespace; - var login = false; - // first we need to binding all the events handler - if (opts.enableAuth && opts.useJwt) { - var namespaces = getNamespaceInOrder(nspSet, publicNamespace); - debugFn$6('namespaces', namespaces); - login = opts.useJwt; // just saying we need to listen to login event - if (token) { - debugFn$6('call createAuthNsps'); - return createAuthNsps(opts, nspMap, token, namespaces) - } - debugFn$6('init with a placeholder'); - return nspClient(publicNamespace, opts) - .then(function (nsp) { - var obj; - - return ({ - nsps: ( obj = {}, obj[ publicNamespace ] = nsp, obj[ namespaces[0] ] = false, obj ), - namespaces: namespaces, - login: login - }); - }) - } - // standard without login - // the stock version should not have a namespace - return nspClient(false, opts) - .then(function (nsp) { - var obj; - - return ({ - nsps: ( obj = {}, obj[publicNamespace] = nsp, obj ), - namespaces: [publicNamespace], - login: login - }); - }) - }; - - - - /** - * This is just copy of the ws version we need to figure - * out how to deal with the roundtrip login later - * @param {object} opts configuration - * @param {object} nspMap namespace with resolvers - * @param {object} ee EventEmitter to pass through - * @return {object} what comes in what goes out - */ - function createClient$1(opts, nspMap, ee) { - // arguments don't change - var args = [opts, nspMap, ee, ioMainHandler]; - return createNsps$1(opts, nspMap, opts.token) - .then( function (ref) { - var nsps = ref.nsps; - var namespaces = ref.namespaces; - var login = ref.login; - - // binding the listeners - and it will listen to LOGOUT event - // to unbind itself, and the above call will bind it again - Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])); - if (login) { - ee.$only(LOGIN_EVENT_NAME, function(token) { - // here we should disconnect all the previous nsps - disconnect(nsps); - // first trigger a LOGOUT event to unbind ee to ws - // ee.$trigger(LOGOUT_EVENT_NAME) // <-- this seems to cause a lot of problems - clearMainEmitEvt(ee, namespaces); - debugFn$6('LOGIN_EVENT_NAME'); - createNsps$1(opts, nspMap, token) - .then(function (newNsps) { - // rebind it - Reflect.apply( - clientEventHandler, - null, - args.concat([newNsps.namespaces, newNsps.nsps]) - ); - }); - }); - } - // return this will also works because the outter call are in promise chain - return { opts: opts, nspMap: nspMap, ee: ee } - }) - } - - /** - * get the create client instance function - * @param {string} type of client - * @return {function} the actual methods - * @public - */ - function createSocketClient(opts, nspMap, ee) { - switch (opts.serverType) { - case SOCKET_IO: - return createClient$1(opts, nspMap, ee) - case WS$1: - return createClient(opts, nspMap, ee) - default: - throw new JsonqlError(SOCKET_NOT_DEFINE_ERR) - } - } - - // generator resolvers - var EMIT_EVT$1 = EMIT_EVT; - var UNKNOWN_RESULT$1 = UNKNOWN_RESULT; - var MY_NAMESPACE$1 = MY_NAMESPACE; - var debugFn$7 = getDebug('generator'); - - /** - * prepare the methods - * @param {object} opts configuration - * @param {object} nspMap resolvers index by their namespace - * @param {object} ee EventEmitter - * @return {object} of resolvers - * @public - */ - function generator(opts, nspMap, ee) { - var obj = {}; - var nspSet = nspMap.nspSet; - for (var namespace in nspSet) { - var list = nspSet[namespace]; - for (var resolverName in list) { - var params = list[resolverName]; - var fn = createResolver(ee, namespace, resolverName, params); - obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee); - } - } - // add error handler - createNamespaceErrorHandler(obj, ee, nspSet); - // add onReady handler - createOnReadyhandler(obj, ee); - // Auth related methods - createAuthMethods(obj, ee, opts); - // this is a helper method for the developer to know the namespace inside - obj.getNsp = function () { - return Object.keys(nspSet) - }; - // output - return obj; - } - - /** - * create the actual function to send message to server - * @param {object} ee EventEmitter instance - * @param {string} namespace this resolver end point - * @param {string} resolverName name of resolver as event name - * @param {object} params from contract - * @return {function} resolver - */ - function createResolver(ee, namespace, resolverName, params) { - // note we pass the new withResult=true option - return function() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return validateAsync$1(args, params.params, true) - .then( function (_args) { return actionCall(ee, namespace, resolverName, _args); } ) - .catch(finalCatch) - } - } - - /** - * just wrapper - * @param {object} ee EventEmitter - * @param {string} namespace where this belongs - * @param {string} resolverName resolver - * @param {array} args arguments - * @return {void} nothing - */ - function actionCall(ee, namespace, resolverName, args) { - if ( args === void 0 ) args = []; - - debugFn$7(("actionCall: " + namespace + " " + resolverName), args); - ee.$trigger(createEvt(namespace, EMIT_EVT$1), [ - resolverName, - toArray$1(args) - ]); - } - - /** - * break out to use in different places to handle the return from server - * @param {object} data from server - * @param {function} resolver from promise - * @param {function} rejecter from promise - * @return {void} nothing - */ - function respondHandler(data, resolver, rejecter) { - if (isKeyInObject(data, 'error')) { - debugFn$7('rejecter called', data.error); - rejecter(data.error); - } else if (isKeyInObject(data, 'data')) { - debugFn$7('resolver called', data.data); - resolver(data.data); - } else { - debugFn$7('UNKNOWN_RESULT', data); - rejecter({message: UNKNOWN_RESULT$1, error: data}); - } - } - - /** - * Add extra property to the resolver - * @param {string} namespace where this belongs - * @param {string} resolverName name as event name - * @param {object} params from contract - * @param {function} fn resolver function - * @param {object} ee EventEmitter - * @return {function} resolver - */ - var setupResolver = function (namespace, resolverName, params, fn, ee) { - // also need to setup a getter to get back the namespace of this resolver - if (Object.getOwnPropertyDescriptor(fn, MY_NAMESPACE$1) === undefined) { - Object.defineProperty(fn, MY_NAMESPACE$1, { - value: namespace, - writeable: false - }); - } - // onResult handler - if (Object.getOwnPropertyDescriptor(fn, RESULT_PROP_NAME) === undefined) { - Object.defineProperty(fn, RESULT_PROP_NAME, { - set: function(resultCallback) { - if (typeof resultCallback === 'function') { - ee.$only( - createEvt(namespace, resolverName, RESULT_PROP_NAME), - function resultHandler(result) { - respondHandler(result, resultCallback, function (error) { - ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error); - }); - } - ); - } - }, - get: function() { - return null; - } - }); - } - // we do need to add the send prop back because it's the only way to deal with - // bi-directional data stream - if (Object.getOwnPropertyDescriptor(fn, MESSAGE_PROP_NAME) === undefined) { - Object.defineProperty(fn, MESSAGE_PROP_NAME, { - set: function(messageCallback) { - // we expect this to be a function - if (typeof messageCallback === 'function') { - // did that add to the callback - var onMessageCallback = function (args) { - respondHandler(args, messageCallback, function (error) { - ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error); - }); - }; - // register the handler for this message event - ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback); - } - }, - get: function() { - return null; // just return nothing - } - }); - } - // add an ERROR_PROP_NAME handler - if (Object.getOwnPropertyDescriptor(fn, ERROR_PROP_NAME) === undefined) { - Object.defineProperty(fn, ERROR_PROP_NAME, { - set: function(resolverErrorHandler) { - if (typeof resolverErrorHandler === 'function') { - // please note ERROR_PROP_NAME can add multiple listners - ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler); - } - }, - get: function() { - return null; - } - }); - } - // pairing with the server vesrion SEND_MSG_PROP_NAME - if (Object.getOwnPropertyDescriptor(fn, SEND_MSG_PROP_NAME) === undefined) { - Object.defineProperty(fn, SEND_MSG_PROP_NAME, { - set: function(messagePayload) { - var result = validateSync$1(toArray$1(messagePayload), params.params, true); - // here is the different we don't throw erro instead we trigger an - // onError - if (result[ERROR_KEY] && result[ERROR_KEY].length) { - ee.$call( - createEvt(namespace, resolverName, ERROR_PROP_NAME), - [JsonqlValidationError(resolverName, result[ERROR_KEY])] - ); - } else { - // there is no return only an action call - actionCall(ee, namespace, resolverName, result[DATA_KEY]); - } - }, - get: function() { - return null; // just return nothing - } - }); - } - return fn; - }; - - /** - * The problem is the namespace can have more than one - * and we only have on onError message - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} nspSet namespace keys - * @return {void} - */ - var createNamespaceErrorHandler = function (obj, ee, nspSet) { - // using the onError as name - // @TODO we should follow the convention earlier - // make this a setter for the obj itself - if (Object.getOwnPropertyDescriptor(obj, ERROR_PROP_NAME) === undefined) { - Object.defineProperty(obj, ERROR_PROP_NAME, { - set: function(namespaceErrorHandler) { - if (typeof namespaceErrorHandler === 'function') { - // please note ERROR_PROP_NAME can add multiple listners - for (var namespace in nspSet) { - // this one is very tricky, we need to make sure the trigger is calling - // with the namespace as well as the error - ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler); - } - } - }, - get: function() { - return null; - } - }); - } - }; - - /** - * This event will fire when the socket.io.on('connection') and ws.onopen - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} nspSet namespace keys - * @return {void} - */ - var createOnReadyhandler = function (obj, ee, nspSet) { - if (Object.getOwnPropertyDescriptor(obj, READY_PROP_NAME) === undefined) { - Object.defineProperty(obj, READY_PROP_NAME, { - set: function(onReadyCallback) { - if (typeof onReadyCallback === 'function') { - // reduce it down to just one flat level - var result = ee.$on(READY_PROP_NAME, onReadyCallback); - } - }, - get: function() { - return null; - } - }); - } - }; - - /** - * Create auth related methods - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} opts configuration - * @return {void} - */ - var createAuthMethods = function (obj, ee, opts) { - if (opts.enableAuth) { - // create an additonal login handler - // we require the token - obj[opts.loginHandlerName] = function (token) { - debugFn$7(opts.loginHandlerName, token); - if (token && isString$1(token)) { - return ee.$trigger(LOGIN_EVENT_NAME, [token]) - } - throw new JsonqlValidationError(opts.loginHandlerName) - }; - // logout event handler - obj[opts.logoutHandlerName] = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - ee.$trigger(LOGOUT_EVENT_NAME, args); - }; - } - }; - - // main api to get the ws-client - - /** - * The main interface to create the wsClient for use - * @param {function} clientGenerator this is an internal way to generate node or browser client - * @return {function} wsClient - * @public - */ - function main(clientGenerator) { - /** - * @param {object} config configuration - * @param {object} [eventEmitter=false] this will be the bridge between clients - * @return {object} wsClient - */ - var wsClient = function (config, eventEmitter) { - if ( eventEmitter === void 0 ) eventEmitter = false; - - return checkOptions(config) - .then(function (opts) { return ({ - opts: opts, - nspMap: processContract(opts), - ee: eventEmitter || new JsonqlWsEvt() - }); } - ) - .then(clientGenerator) - .then( - function (ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - return createSocketClient(opts, nspMap, ee); - } - ) - .then( - function (ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - return generator(opts, nspMap, ee); - } - ) - .catch(function (err) { - console.error('jsonql-ws-client init error', err); - }) - }; - // use the Object.addProperty trick - Object.defineProperty(wsClient, 'CLIENT_TYPE_INFO', { - value: 'version: 1.0.0-beta.1 module: umd', - writable: false - }); - return wsClient; - } - - // This is the module entry point - - var index = main(clientGenerator); - - return index; - -})); -//# sourceMappingURL=jsonql-ws-client.js.map diff --git a/packages/ws-client/dist/jsonql-ws-client.js.map b/packages/ws-client/dist/jsonql-ws-client.js.map deleted file mode 100644 index 12a7d8d7..00000000 --- a/packages/ws-client/dist/jsonql-ws-client.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonql-ws-client.js","sources":["../node_modules/jsonql-jwt/src/client/socketio/socket-io-client.js","../node_modules/jsonql-jwt/src/client/socketio/handshake-login.js","../node_modules/jsonql-errors/src/500-error.js","../node_modules/jsonql-errors/src/enum-error.js","../node_modules/jsonql-errors/src/type-error.js","../node_modules/jsonql-errors/src/checker-error.js","../node_modules/jsonql-errors/src/validation-error.js","../node_modules/jsonql-errors/src/server-error.js","../node_modules/jsonql-jwt/src/client/socketio/roundtrip-login.js","../node_modules/rollup-plugin-node-globals/src/global.js","../node_modules/lodash-es/_objectToString.js","../node_modules/lodash-es/isObjectLike.js","../node_modules/lodash-es/_arrayMap.js","../node_modules/lodash-es/isArray.js","../node_modules/lodash-es/isObject.js","../node_modules/lodash-es/identity.js","../node_modules/lodash-es/_toSource.js","../node_modules/lodash-es/_getValue.js","../node_modules/lodash-es/_apply.js","../node_modules/lodash-es/_copyArray.js","../node_modules/lodash-es/_shortOut.js","../node_modules/lodash-es/constant.js","../node_modules/lodash-es/_baseFindIndex.js","../node_modules/lodash-es/_baseIsNaN.js","../node_modules/lodash-es/_strictIndexOf.js","../node_modules/lodash-es/_isIndex.js","../node_modules/lodash-es/eq.js","../node_modules/lodash-es/isLength.js","../node_modules/lodash-es/_isPrototype.js","../node_modules/lodash-es/_baseTimes.js","../node_modules/lodash-es/stubFalse.js","../node_modules/lodash-es/_baseUnary.js","../node_modules/lodash-es/_overArg.js","../node_modules/lodash-es/_nativeKeysIn.js","../node_modules/lodash-es/_hashDelete.js","../node_modules/lodash-es/_listCacheClear.js","../node_modules/lodash-es/_isKeyable.js","../node_modules/lodash-es/_arrayPush.js","../node_modules/lodash-es/_baseSlice.js","../node_modules/lodash-es/_hasUnicode.js","../node_modules/lodash-es/_asciiToArray.js","../node_modules/lodash-es/_unicodeToArray.js","../node_modules/lodash-es/_stackDelete.js","../node_modules/lodash-es/_stackGet.js","../node_modules/lodash-es/_stackHas.js","../node_modules/lodash-es/_arrayFilter.js","../node_modules/lodash-es/stubArray.js","../node_modules/lodash-es/_setCacheAdd.js","../node_modules/lodash-es/_setCacheHas.js","../node_modules/lodash-es/_arraySome.js","../node_modules/lodash-es/_cacheHas.js","../node_modules/lodash-es/_mapToArray.js","../node_modules/lodash-es/_setToArray.js","../node_modules/lodash-es/_matchesStrictComparable.js","../node_modules/lodash-es/_baseHasIn.js","../node_modules/lodash-es/_baseProperty.js","../node_modules/lodash-es/_createBaseFor.js","../node_modules/lodash-es/_safeGet.js","../node_modules/lodash-es/_baseFindKey.js","../node_modules/lodash-es/isNull.js","../node_modules/lodash-es/isUndefined.js","../node_modules/lodash-es/negate.js","../node_modules/jsonql-params-validator/src/not-empty.js","../node_modules/jsonql-params-validator/src/number.js","../node_modules/jsonql-params-validator/src/string.js","../node_modules/jsonql-params-validator/src/boolean.js","../node_modules/jsonql-params-validator/src/any.js","../node_modules/jsonql-params-validator/src/constants.js","../node_modules/jsonql-params-validator/src/combine.js","../node_modules/jsonql-params-validator/src/array.js","../node_modules/jsonql-params-validator/src/object.js","../node_modules/jsonql-params-validator/src/validator.js","../node_modules/jsonql-params-validator/src/is-in-array.js","../node_modules/jsonql-params-validator/src/options/run-validation.js","../node_modules/jsonql-params-validator/src/options/check-options-async.js","../node_modules/jsonql-params-validator/src/options/construct-config.js","../node_modules/jsonql-params-validator/src/options/index.js","../node_modules/jsonql-params-validator/src/check-is-contract.js","../node_modules/jsonql-params-validator/src/params-api.js","../node_modules/jsonql-params-validator/index.js","../node_modules/jsonql-jwt/src/client/utils/group-by-namespace.js","../node_modules/jsonql-jwt/src/client/utils/chain-promises.js","../node_modules/jwt-decode/lib/atob.js","../node_modules/jsonql-jwt/src/client/ws/ws.js","../src/utils/constants.js","../src/utils/client-generator.js","../src/utils/create-nsp-client.js","../node_modules/nb-event-service/src/hash-code.js","../node_modules/nb-event-service/src/suspend.js","../node_modules/nb-event-service/src/store-service.js","../node_modules/nb-event-service/src/event-service.js","../node_modules/nb-event-service/index.js","../src/utils/process-contract.js","../src/utils/index.js","../src/client-event-handler.js","../src/ws/extract-ws-payload.js","../src/ws/ws-main-handler.js","../src/ws/create-client.js","../src/ws/index.js","../src/io/create-client.js","../src/generator.js","../src/main.js","../index.js"],"sourcesContent":["// this should work on browser as well as node\n// import io from 'socket.io-cilent'\n\n/**\n * Create a normal client\n * @param {object} io socket io instance\n * @param {string} url end point\n * @param {object} [options={}] configuration\n * @return {object} nsp instance\n */\nexport default function socketIoClient(io, url, options = {}) {\n return io.connect(url, options)\n}\n","// handshake login\nimport { TOKEN_PARAM_NAME, DEFAULT_WS_WAIT_TIME } from 'jsonql-constants';\nimport socketIoClient from './socket-io-client'\n\n/**\n * Create a async version to match up the rest of the api\n * @param {object} io socket io instance\n * @param {string} url end point\n * @param {object} [options={}] configuration\n * @return {object} Promise resolve to nsp instance\n */\nexport function socketIoClientAsync(...args) {\n return Promise.resolve(\n Reflect.apply(socketIoClient, null, args)\n )\n}\n\n/**\n * Login during handshake\n * @param {object} io the new socket.io instance\n * @param {string} token to send\n * @param {object} [options = {}] extra options\n * @return {object} the io object itself\n */\nexport function socketIoHandshakeLogin(io, url, token, options = {}) {\n const wait = options.timeout || DEFAULT_WS_WAIT_TIME;\n const config = Object.assign({}, options, {\n query: [TOKEN_PARAM_NAME, token].join('=')\n })\n let timer;\n const nsp = socketIoClient(io, url, config)\n return new Promise((resolver, rejecter) => {\n timer = setTimeout(() => {\n rejecter()\n }, wait)\n nsp.on('connect', () => {\n console.info('socketIoHandshakeLogin connected')\n resolver(nsp)\n clearTimeout(timer)\n })\n })\n}\n","/**\n * This is a custom error to throw when server throw a 500\n * This help us to capture the right error, due to the call happens in sequence\n * @param {string} message to tell what happen\n * @param {mixed} extra things we want to add, 500?\n */\nexport default class Jsonql500Error extends Error {\n constructor(...args) {\n super(...args);\n\n this.message = args[0];\n this.detail = args[1];\n\n this.className = Jsonql500Error.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, Jsonql500Error);\n }\n }\n\n static get statusCode() {\n return 500;\n }\n\n static get name() {\n return 'Jsonql500Error';\n }\n\n}\n","// this get throw from within the checkOptions when run through the enum failed\nexport default class JsonqlEnumError extends Error {\n constructor(...args) {\n super(...args);\n \n this.message = args[0];\n this.detail = args[1];\n\n this.className = JsonqlEnumError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlEnumError);\n }\n }\n\n static get name() {\n return 'JsonqlEnumError';\n }\n}\n","// this will throw from inside the checkOptions\nexport default class JsonqlTypeError extends Error {\n constructor(...args) {\n super(...args);\n\n this.message = args[0];\n this.detail = args[1];\n\n this.className = JsonqlTypeError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlTypeError);\n }\n }\n\n static get name() {\n return 'JsonqlTypeError';\n }\n}\n","// allow supply a custom checker function\n// if that failed then we throw this error\nexport default class JsonqlCheckerError extends Error {\n constructor(...args) {\n super(...args);\n this.message = args[0];\n this.detail = args[1];\n\n this.className = JsonqlCheckerError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlCheckerError);\n }\n }\n\n static get name() {\n return 'JsonqlCheckerError';\n }\n}\n","// custom validation error class\n// when validaton failed\nexport default class JsonqlValidationError extends Error {\n constructor(...args) {\n super(...args);\n\n this.message = args[0];\n this.detail = args[1];\n\n this.className = JsonqlValidationError.name;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, JsonqlValidationError);\n }\n }\n\n static get name() {\n return 'JsonqlValidationError';\n }\n}\n","// this is from an example from Koa team to use for internal middleware ctx.throw\n// but after the test the res.body part is unable to extract the required data\n// I keep this one here for future reference\n\nexport default class JsonqlServerError extends Error {\n\n constructor(statusCode, message) {\n super(message);\n this.statusCode = statusCode;\n this.className = JsonqlServerError.name;\n }\n\n static get name() {\n return 'JsonqlServerError';\n }\n}\n","// import { isString } from 'jsonql-params-validator';\nimport { JsonqlValidationError } from 'jsonql-errors';\nimport socketIoClient from './socket-io-client'\n/**\n * The core method of the socketJwt client side\n * @param {object} socket the socket.io connected instance\n * @param {string} token for validation\n * @param {function} onAuthenitcated callback when authenticated\n * @param {function} onUnauthorized callback when authorized\n * @return {void}\n */\nconst socketIoLoginAction = (socket, token, onAuthenticated, onUnauthorized) => {\n socket\n .emit('authenticate', { token })\n .on('authenticated', onAuthenticated)\n .on('unauthorized', onUnauthorized)\n}\n\n/**\n * completely rethink about how the browser version should be!\n *\n */\nexport default function socketIoRoundtripLogin(io, url, token, options = {}) {\n const socket = socketIoClient(io, url)\n return new Promise((resolver, rejecter) => {\n socketIoLoginAction(socket, token, () => resolver(socket) , rejecter);\n })\n}\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n","/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n","/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nexport default safeGet;\n","/**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\nfunction baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n}\n\nexport default baseFindKey;\n","/**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\nfunction isNull(value) {\n return value === null;\n}\n\nexport default isNull;\n","/**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\nfunction isUndefined(value) {\n return value === undefined;\n}\n\nexport default isUndefined;\n","/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n","/**\n * Check several parameter that there is something in the param\n * @param {*} param input\n * @return {boolean}\n */\nimport { trim, isArray } from 'lodash-es'\n\nexport default a => {\n if (isArray(a)) {\n return true;\n }\n return a !== undefined && a !== null && trim(a) !== '';\n}\n","// validator numbers\n// import { NUMBER_TYPES } from './constants';\nimport { isNaN, isString } from 'lodash-es'\n/**\n * @2015-05-04 found a problem if the value is a number like string\n * it will pass, so add a check if it's string before we pass to next\n * @param {number} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsNumber = function(value) {\n return isString(value) ? false : !isNaN( parseFloat(value) )\n}\n\nexport default checkIsNumber\n","// validate string type\nimport { isString, trim } from 'lodash-es'\n/**\n * @param {string} value expected value\n * @return {boolean} true if OK\n */\nconst checkIsString = function(value) {\n return (trim(value) !== '') ? isString(value) : false;\n}\n\nexport default checkIsString;\n","// check for boolean\nimport { isBoolean } from 'lodash-es'\n/**\n * @param {boolean} value expected\n * @return {boolean} true if OK\n */\nconst checkIsBoolean = function(value) {\n return isBoolean(value);\n};\n\nexport default checkIsBoolean\n","// validate any thing only check if there is something\nimport { isNull, trim, isUndefined } from 'lodash-es'\n/**\n * @param {*} value the value\n * @param {boolean} [checkNull=true] strict check if there is null value\n * @return {boolean} true is OK\n */\nconst checkIsAny = function(value, checkNull = true) {\n if (!isUndefined(value) && value !== '' && trim(value) !== '') {\n if (checkNull === false || (checkNull === true && !isNull(value))) {\n return true;\n }\n }\n return false;\n};\n\nexport default checkIsAny\n","// Good practice rule - No magic number\n\nexport const ARGS_NOT_ARRAY_ERR = `args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)`;\nexport const PARAMS_NOT_ARRAY_ERR = `params is not an array! Did something gone wrong when you generate the contract.json?`;\nexport const EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!';\nexport const UNUSUAL_CASE_ERR = 'This is an unusual situation where the arguments are more than the params, but not mark as spread';\n\n// re-export\nimport * as JSONQL_CONSTANTS from 'jsonql-constants';\n// @TODO the jsdoc return array. and we should also allow array syntax\nexport const DEFAULT_TYPE = JSONQL_CONSTANTS.DEFAULT_TYPE;\nexport const ARRAY_TYPE_LFT = JSONQL_CONSTANTS.ARRAY_TYPE_LFT;\nexport const ARRAY_TYPE_RGT = JSONQL_CONSTANTS.ARRAY_TYPE_RGT;\n\nexport const TYPE_KEY = JSONQL_CONSTANTS.TYPE_KEY;\nexport const OPTIONAL_KEY = JSONQL_CONSTANTS.OPTIONAL_KEY;\nexport const ENUM_KEY = JSONQL_CONSTANTS.ENUM_KEY;\nexport const ARGS_KEY = JSONQL_CONSTANTS.ARGS_KEY;\nexport const CHECKER_KEY = JSONQL_CONSTANTS.CHECKER_KEY;\nexport const ALIAS_KEY = JSONQL_CONSTANTS.ALIAS_KEY;\n\nexport const ARRAY_TYPE = JSONQL_CONSTANTS.ARRAY_TYPE;\nexport const OBJECT_TYPE = JSONQL_CONSTANTS.OBJECT_TYPE;\nexport const STRING_TYPE = JSONQL_CONSTANTS.STRING_TYPE;\nexport const BOOLEAN_TYPE = JSONQL_CONSTANTS.BOOLEAN_TYPE;\nexport const NUMBER_TYPE = JSONQL_CONSTANTS.NUMBER_TYPE;\nexport const KEY_WORD = JSONQL_CONSTANTS.KEY_WORD;\nexport const OR_SEPERATOR = JSONQL_CONSTANTS.OR_SEPERATOR;\n\n// not actually in use\n// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES;\n","// primitive types\nimport checkIsNumber from './number'\nimport checkIsString from './string'\nimport checkIsBoolean from './boolean'\nimport checkIsAny from './any'\nimport { NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE } from './constants'\n\n/**\n * this is a wrapper method to call different one based on their type\n * @param {string} type to check\n * @return {function} a function to handle the type\n */\nconst combineFn = function(type) {\n switch (type) {\n case NUMBER_TYPE:\n return checkIsNumber;\n case STRING_TYPE:\n return checkIsString;\n case BOOLEAN_TYPE:\n return checkIsBoolean;\n default:\n return checkIsAny;\n }\n}\n\nexport default combineFn\n","// validate array type\nimport { isArray, trim } from 'lodash-es'\nimport combineFn from './combine'\nimport {\n ARRAY_TYPE_LFT,\n ARRAY_TYPE_RGT,\n OR_SEPERATOR\n} from './constants'\n\n/**\n * @param {array} value expected\n * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well\n * @return {boolean} true if OK\n */\nexport const checkIsArray = function(value, type='') {\n if (isArray(value)) {\n if (type === '' || trim(type)==='') {\n return true;\n }\n // we test it in reverse\n // @TODO if the type is an array (OR) then what?\n // we need to take into account this could be an array\n const c = value.filter(v => !combineFn(type)(v))\n return !(c.length > 0)\n }\n return false;\n}\n\n/**\n * check if it matches the array. pattern\n * @param {string} type\n * @return {boolean|array} false means NO, always return array\n */\nexport const isArrayLike = function(type) {\n // @TODO could that have something like array<> instead of array.<>? missing the dot?\n // because type script is Array without the dot\n if (type.indexOf(ARRAY_TYPE_LFT) > -1 && type.indexOf(ARRAY_TYPE_RGT) > -1) {\n const _type = type.replace(ARRAY_TYPE_LFT, '').replace(ARRAY_TYPE_RGT, '')\n if (_type.indexOf(OR_SEPERATOR)) {\n return _type.split(OR_SEPERATOR)\n }\n return [_type]\n }\n return false;\n}\n\n/**\n * we might encounter something like array. then we need to take it apart\n * @param {object} p the prepared object for processing\n * @param {string|array} type the type came from \n * @return {boolean} for the filter to operate on\n */\nexport const arrayTypeHandler = function(p, type) {\n const { arg } = p;\n // need a special case to handle the OR type\n // we need to test the args instead of the type(s)\n if (type.length > 1) {\n return !arg.filter(v => (\n !(type.length > type.filter(t => !combineFn(t)(v)).length)\n )).length;\n }\n // type is array so this will be or!\n return type.length > type.filter(t => !checkIsArray(arg, t)).length;\n}\n","// validate object type\nimport { isPlainObject, isUndefined, filter } from 'lodash-es'\nimport combineFn from './combine'\nimport { checkIsArray, isArrayLike, arrayTypeHandler } from './array'\n/**\n * @TODO if provide with the keys then we need to check if the key:value type as well\n * @param {object} value expected\n * @param {array} [keys=null] if it has the keys array to compare as well\n * @return {boolean} true if OK\n */\nexport const checkIsObject = function(value, keys=null) {\n if (isPlainObject(value)) {\n if (!keys) {\n return true;\n }\n if (checkIsArray(keys)) {\n // please note we DON'T care if some is optional\n // plese refer to the contract.json for the keys\n return !keys.filter(key => {\n let _value = value[key.name];\n return !(key.type.length > key.type.filter(type => {\n let tmp;\n if (!isUndefined(_value)) {\n if ((tmp = isArrayLike(type)) !== false) {\n return !arrayTypeHandler({arg: _value}, tmp)\n // return tmp.filter(t => !checkIsArray(_value, t)).length;\n // @TODO there might be an object within an object with keys as well :S\n }\n return !combineFn(type)(_value)\n }\n return true;\n }).length)\n }).length;\n }\n }\n return false;\n}\n\n/**\n * fold this into it's own function to handler different object type\n * @param {object} p the prepared object for process\n * @return {boolean}\n */\nexport const objectTypeHandler = function(p) {\n const { arg, param } = p;\n let _args = [arg];\n if (Array.isArray(param.keys) && param.keys.length) {\n _args.push(param.keys)\n }\n // just simple check\n return checkIsObject.apply(null, _args)\n}\n","// move the index.js code here that make more sense to find where things are\nimport { isUndefined } from 'lodash-es'\nimport {\n checkIsArray,\n isArrayLike,\n arrayTypeHandler,\n objectTypeHandler,\n checkIsObject,\n combineFn,\n notEmpty\n} from './index'\nimport {\n DEFAULT_TYPE,\n ARRAY_TYPE,\n OBJECT_TYPE,\n ARGS_NOT_ARRAY_ERR,\n PARAMS_NOT_ARRAY_ERR,\n EXCEPTION_CASE_ERR,\n UNUSUAL_CASE_ERR\n} from './constants'\nimport { DATA_KEY, ERROR_KEY } from 'jsonql-constants'\nimport { JsonqlError } from 'jsonql-errors'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:validator')\n// also export this for use in other places\n\n/**\n * We need to handle those optional parameter without a default value\n * @param {object} params from contract.json\n * @return {boolean} for filter operation false is actually OK\n */\nconst optionalHandler = function( params ) {\n const { arg, param } = params;\n if (notEmpty(arg)) {\n // debug('call optional handler', arg, params);\n // loop through the type in param\n return !(param.type.length > param.type.filter(type =>\n validateHandler(type, params)\n ).length)\n }\n return false;\n}\n\n/**\n * actually picking the validator\n * @param {*} type for checking\n * @param {*} value for checking\n * @return {boolean} true on OK\n */\nconst validateHandler = function(type, value) {\n let tmp;\n switch (true) {\n case type === OBJECT_TYPE:\n // debugFn('call OBJECT_TYPE')\n return !objectTypeHandler(value)\n case type === ARRAY_TYPE:\n // debugFn('call ARRAY_TYPE')\n return !checkIsArray(value.arg)\n // @TODO when the type is not present, it always fall through here\n // so we need to find a way to actually pre-check the type first\n // AKA check the contract.json map before running here\n case (tmp = isArrayLike(type)) !== false:\n // debugFn('call ARRAY_LIKE: %O', value)\n return !arrayTypeHandler(value, tmp)\n default:\n return !combineFn(type)(value.arg)\n }\n}\n\n/**\n * it get too longer to fit in one line so break it out from the fn below\n * @param {*} arg value\n * @param {object} param config\n * @return {*} value or apply default value\n */\nconst getOptionalValue = function(arg, param) {\n if (!isUndefined(arg)) {\n return arg;\n }\n return (param.optional === true && !isUndefined(param.defaultvalue) ? param.defaultvalue : null)\n}\n\n/**\n * padding the arguments with defaultValue if the arguments did not provide the value\n * this will be the name export\n * @param {array} args normalized arguments\n * @param {array} params from contract.json\n * @return {array} merge the two together\n */\nexport const normalizeArgs = function(args, params) {\n // first we should check if this call require a validation at all\n // there will be situation where the function doesn't need args and params\n if (!checkIsArray(params)) {\n // debugFn('params value', params)\n throw new JsonqlError(PARAMS_NOT_ARRAY_ERR)\n }\n if (params.length === 0) {\n return [];\n }\n if (!checkIsArray(args)) {\n throw new JsonqlError(ARGS_NOT_ARRAY_ERR)\n }\n // debugFn(args, params);\n // fall through switch\n switch(true) {\n case args.length == params.length: // standard\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i]\n }\n ));\n case params[0].variable === true: // using spread syntax\n const type = params[0].type;\n return args.map((arg, i) => (\n {\n arg,\n index: i, // keep the index for reference\n param: params[i] || { type, name: '_' }\n }\n ));\n // with optional defaultValue parameters\n case args.length < params.length:\n return params.map((param, i) => (\n {\n param,\n index: i,\n arg: getOptionalValue(args[i], param),\n optional: param.optional || false\n }\n ));\n // this one pass more than it should have anything after the args.length will be cast as any type\n case args.length > params.length && params.length === 1:\n // this happens when we have those array. type\n let tmp, _type = [ DEFAULT_TYPE ];\n // we only looking at the first one, this might be a @BUG!\n if ((tmp = isArrayLike(params[0].type[0])) !== false) {\n _type = tmp;\n }\n // if not then we fall back to the following\n return args.map((arg, i) => (\n {\n arg,\n index: i,\n param: params[i] || { type: _type, name: '_' }\n }\n ));\n // @TODO find out if there is more cases not cover\n default: // this should never happen\n // debugFn('args', args)\n // debugFn('params', params)\n // this is unknown therefore we just throw it!\n throw new JsonqlError(EXCEPTION_CASE_ERR, { args, params })\n }\n}\n\n// what we want is after the validaton we also get the normalized result\n// which is with the optional property if the argument didn't provide it\n/**\n * process the array of params back to their arguments\n * @param {array} result the params result\n * @return {array} arguments\n */\nconst processReturn = result => result.map(r => r.arg)\n\n/**\n * validator main interface\n * @param {array} args the arguments pass to the method call\n * @param {array} params from the contract for that method\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {array} empty array on success, or failed parameter and reasons\n */\nexport const validateSync = function(args, params, withResult = false) {\n let cleanArgs = normalizeArgs(args, params)\n let checkResult = cleanArgs.filter(p => {\n if (p.param.optional === true) {\n return optionalHandler(p)\n }\n // because array of types means OR so if one pass means pass\n return !(p.param.type.length > p.param.type.filter(\n type => validateHandler(type, p)\n ).length)\n })\n // using the same convention we been using all this time\n return !withResult ? checkResult : {\n [ERROR_KEY]: checkResult,\n [DATA_KEY]: processReturn(cleanArgs)\n }\n}\n\n/**\n * A wrapper method that return promise\n * @param {array} args arguments\n * @param {array} params from contract.json\n * @param {boolean} [withResul=false] if true then this will return the normalize result as well\n * @return {object} promise.then or catch\n */\nexport const validateAsync = function(args, params, withResult = false) {\n return new Promise((resolver, rejecter) => {\n const result = validateSync(args, params, withResult)\n if (withResult) {\n return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY])\n : resolver(result[DATA_KEY])\n }\n // the different is just in the then or catch phrase\n return result.length ? rejecter(result) : resolver([])\n })\n}\n","/**\n * @param {array} arr Array for check\n * @param {*} value target\n * @return {boolean} true on successs\n */\nconst isInArray = function(arr, value) {\n return !!arr.filter(a => a === value).length;\n}\n\nexport default isInArray\n","// breaking the whole thing up to see what cause the multiple calls issue\n\nimport { isFunction, merge, mapValues } from 'lodash-es'\n\nimport {\n TYPE_KEY,\n OPTIONAL_KEY,\n ENUM_KEY,\n ARGS_KEY,\n CHECKER_KEY,\n KEY_WORD\n} from '../constants'\nimport {\n JsonqlEnumError,\n JsonqlTypeError,\n JsonqlCheckerError\n} from 'jsonql-errors'\nimport { checkIsArray } from '../array'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:validation')\n\n/**\n * just make sure it returns an array to use\n * @param {*} arg input\n * @return {array} output\n */\nconst toArray = arg => checkIsArray(arg) ? arg : [arg]\n\n/**\n * DIY in array\n * @param {array} arr to check against\n * @param {*} value to check\n * @return {boolean} true on OK\n */\nconst inArray = (arr, value) => (\n !!arr.filter(v => v === value).length\n)\n\n/**\n * break out to make the code easier to read\n * @param {object} value to process\n * @param {function} cb the validateSync\n * @return {array} empty on success\n */\nfunction validateHandler(value, cb) {\n // cb is the validateSync methods\n let args = [\n [ value[ARGS_KEY] ],\n [{\n [TYPE_KEY]: toArray(value[TYPE_KEY]),\n [OPTIONAL_KEY]: value[OPTIONAL_KEY]\n }]\n ]\n // debugFn('validateHandler', args)\n return Reflect.apply(cb, null, args)\n}\n\n/**\n * Check against the enum value if it's provided\n * @param {*} value to check\n * @param {*} enumv to check against if it's not false\n * @return {boolean} true on OK\n */\nconst enumHandler = (value, enumv) => {\n if (checkIsArray(enumv)) {\n return inArray(enumv, value)\n }\n return true;\n}\n\n/**\n * Allow passing a function to check the value\n * There might be a problem here if the function is incorrect\n * and that will makes it hard to debug what is going on inside\n * @TODO there could be a few feature add to this one under different circumstance\n * @param {*} value to check\n * @param {function} checker for checking\n */\nconst checkerHandler = (value, checker) => {\n try {\n return isFunction(checker) ? checker.apply(null, [value]) : false;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Taken out from the runValidaton this only validate the required values\n * @param {array} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {array} of configuration values\n */\nfunction runValidationAction(cb) {\n return (value, key) => {\n // debugFn('runValidationAction', key, value)\n if (value[KEY_WORD]) {\n return value[ARGS_KEY]\n }\n const check = validateHandler(value, cb)\n if (check.length) {\n // debugFn('runValidationAction', key, value)\n throw new JsonqlTypeError(key, check)\n }\n if (value[ENUM_KEY] !== false && !enumHandler(value[ARGS_KEY], value[ENUM_KEY])) {\n throw new JsonqlEnumError(key)\n }\n if (value[CHECKER_KEY] !== false && !checkerHandler(value[ARGS_KEY], value[CHECKER_KEY])) {\n throw new JsonqlCheckerError(key)\n }\n return value[ARGS_KEY]\n }\n}\n\n/**\n * @param {object} args from the config2argsAction\n * @param {function} cb validateSync\n * @return {object} of configuration values\n */\nexport default function runValidation(args, cb) {\n const [ argsForValidate, pristineValues ] = args;\n // turn the thing into an array and see what happen here\n // debugFn('_args', argsForValidate)\n const result = mapValues(argsForValidate, runValidationAction(cb))\n return merge(result, pristineValues)\n}\n","// this is port back from the client to share across all projects\nimport { merge } from 'lodash-es'\nimport { prepareArgsForValidation } from './prepare-args-for-validation'\nimport runValidation from './run-validation'\n\n// import debug from 'debug'\n// const debugFn = debug('jsonql-params-validator:check-options-async')\n\n/**\n * Quick transform\n * @param {object} config that one\n * @param {object} appProps mutation configuration options\n * @return {object} put that arg into the args\n */\nconst configToArgs = (config, appProps) => {\n return Promise.resolve(\n prepareArgsForValidation(config, appProps)\n )\n}\n\n/**\n * @param {object} config user provide configuration option\n * @param {object} appProps mutation configuration options\n * @param {object} constProps the immutable configuration options\n * @param {function} cb the validateSync method\n * @return {object} Promise resolve merge config object\n */\nexport default function(config = {}, appProps, constProps, cb) {\n return configToArgs(config, appProps)\n .then(args1 => {\n // debugFn('args', args1)\n return runValidation(args1, cb)\n })\n // next if every thing good then pass to final merging\n .then(args2 => merge({}, args2, constProps))\n}\n","// create function to construct the config entry so we don't need to keep building object\nimport {\n ARGS_KEY,\n TYPE_KEY,\n CHECKER_KEY,\n ENUM_KEY,\n OPTIONAL_KEY,\n ALIAS_KEY\n} from 'jsonql-constants';\nimport { checkIsArray } from '../array';\nimport checkIsBoolean from '../boolean';\nimport { isFunction, isString } from 'lodash-es';\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:construct-config');\n/**\n * @param {*} args value\n * @param {string} type for value\n * @param {boolean} [optional=false]\n * @param {boolean|array} [enumv=false]\n * @param {boolean|function} [checker=false]\n * @return {object} config entry\n */\nexport default function(args, type, optional=false, enumv=false, checker=false, alias=false) {\n let base = {\n [ARGS_KEY]: args,\n [TYPE_KEY]: type\n };\n if (optional === true) {\n base[OPTIONAL_KEY] = true;\n }\n if (checkIsArray(enumv)) {\n base[ENUM_KEY] = enumv;\n }\n if (isFunction(checker)) {\n base[CHECKER_KEY] = checker;\n }\n if (isString(alias)) {\n base[ALIAS_KEY] = alias;\n }\n return base;\n};\n","// export also create wrapper methods\nimport checkOptionsAsync from './check-options-async'\nimport checkOptionsSync from './check-options-sync'\nimport constructConfigFn from './construct-config'\nimport {\n ENUM_KEY,\n CHECKER_KEY,\n ALIAS_KEY,\n OPTIONAL_KEY\n} from 'jsonql-constants'\n\n// import debug from 'debug';\n// const debugFn = debug('jsonql-params-validator:options:index');\n\n/**\n * This has a different interface\n * @param {*} value to supply\n * @param {string|array} type for checking\n * @param {object} params to map against the config check\n * @param {array} params.enumv NOT enum\n * @param {boolean} params.optional false then nothing\n * @param {function} params.checker need more work on this one later\n * @param {string} params.alias mostly for cmd\n */\nconst createConfig = (value, type, params = {}) => {\n // Note the enumv not ENUM\n // const { enumv, optional, checker, alias } = params;\n // let args = [value, type, optional, enumv, checker, alias];\n const {\n [OPTIONAL_KEY]: o,\n [ENUM_KEY]: e,\n [CHECKER_KEY]: c,\n [ALIAS_KEY]: a\n } = params;\n return constructConfigFn.apply(null, [value, type, o, e, c, a])\n}\n\n// for testing purpose\nconst JSONQL_PARAMS_VALIDATOR_INFO = '__PLACEHOLDER__';\n\n/**\n * We recreate the method here to avoid the circlar import\n * @param {object} config user supply configuration\n * @param {object} appProps mutation options\n * @param {object} [constantProps={}] optional: immutation options\n * @return {object} all checked configuration\n */\nconst checkConfigAsync = function(validateSync) {\n return function(config, appProps, constantProps= {}) {\n return checkOptionsAsync(config, appProps, constantProps, validateSync)\n }\n}\n\n// copy of above but it's sync\nconst checkConfig = function(validateSync) {\n return function(config, appProps, constantProps = {}) {\n return checkOptionsSync(config, appProps, constantProps, validateSync)\n }\n}\n\n// re-export\nexport {\n createConfig,\n constructConfigFn,\n checkConfigAsync,\n checkConfig,\n JSONQL_PARAMS_VALIDATOR_INFO\n}\n","// since this need to use everywhere might as well include in the validator\nimport { QUERY_NAME, MUTATION_NAME, SOCKET_NAME } from 'jsonql-constants'\nimport checkKeyInObject from './check-key-in-object'\nimport { checkIsObject } from './object'\n\nexport default function(contract) {\n return checkIsObject(contract)\n && (\n checkKeyInObject(contract, QUERY_NAME)\n || checkKeyInObject(contract, MUTATION_NAME)\n || checkKeyInObject(contract, SOCKET_NAME)\n )\n}\n","// craete several helper function to construct / extract the payload\n// and make sure they are all the same\nimport {\n PAYLOAD_PARAM_NAME,\n CONDITION_PARAM_NAME,\n RESOLVER_PARAM_NAME,\n QUERY_ARG_NAME\n} from 'jsonql-constants'\nimport { JsonqlValidationError } from 'jsonql-errors'\n\nimport isString from './string'\nimport { checkIsArray } from './array'\nimport { checkIsObject } from './object'\n\n// make sure it's an object\nconst formatPayload = payload => isString(payload) ? JSON.parse(payload) : payload;\n\n/**\n * Get name from the payload (ported back from jsonql-koa)\n * @param {*} payload to extract from\n * @return {string} name\n */\nexport function getNameFromPayload(payload) {\n return Object.keys(payload)[0]\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {array} [args=[]] from the ...args\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createQuery(resolverName, args = [], jsonp = false) {\n if (isString(resolverName) && checkIsArray(args)) {\n let payload = { [QUERY_ARG_NAME]: args }\n if (jsonp === true) {\n return payload;\n }\n return { [resolverName]: payload }\n }\n throw new JsonqlValidationError(`[createQuery] expect resolverName to be string and args to be array!`, { resolverName, args })\n}\n\n// string version of the above\nexport function createQueryStr(resolverName, args = [], jsonp = false) {\n return JSON.stringify(createQuery(resolverName, args, jsonp))\n}\n\n/**\n * @param {string} resolverName name of function\n * @param {*} payload to send\n * @param {object} [condition={}] for what\n * @param {boolean} [jsonp = false] add v1.3.0 to koa\n * @return {object} formatted argument\n */\nexport function createMutation(resolverName, payload, condition = {}, jsonp = false) {\n const _payload = {\n [PAYLOAD_PARAM_NAME]: payload,\n [CONDITION_PARAM_NAME]: condition\n }\n if (jsonp === true) {\n return _payload;\n }\n if (isString(resolverName)) {\n return { [resolverName]: _payload }\n }\n throw new JsonqlValidationError(`[createMutation] expect resolverName to be string!`, { resolverName, payload, condition })\n}\n\n// string version of above\nexport function createMutationStr(resolverName, payload, condition = {}, jsonp = false) {\n return JSON.stringify(createMutation(resolverName, payload, condition, jsonp))\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getQueryFromArgs(resolverName, payload) {\n if (resolverName && checkIsObject(payload)) {\n const args = payload[resolverName];\n if (args[QUERY_ARG_NAME]) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [QUERY_ARG_NAME]: args[QUERY_ARG_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * extra the payload back\n * @param {*} payload from http call\n * @return {object} resolverName and args\n */\nexport function getQueryFromPayload(payload) {\n const p = formatPayload(payload);\n const resolverName = getNameFromPayload(p)\n const result = getQueryFromArgs(resolverName, p)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getQueryArgs] Payload is malformed!', payload)\n}\n\n/**\n * Further break down from method below for use else where\n * @param {string} resolverName name of fn\n * @param {object} payload payload\n * @return {object|boolean} false on failed\n */\nexport function getMutationFromArgs(resolverName, payload) {\n if (resolverName && checkIsObject(payload)) {\n const args = payload[resolverName]\n if (args) {\n return {\n [RESOLVER_PARAM_NAME]: resolverName,\n [PAYLOAD_PARAM_NAME]: args[PAYLOAD_PARAM_NAME],\n [CONDITION_PARAM_NAME]: args[CONDITION_PARAM_NAME]\n }\n }\n }\n return false;\n}\n\n/**\n * @param {object} payload\n * @return {object} resolverName, payload, conditon\n */\nexport function getMutationFromPayload(payload) {\n const p = formatPayload(payload);\n const resolverName = getNameFromPayload(p)\n const result = getMutationFromArgs(resolverName, p)\n if (result !== false) {\n return result;\n }\n throw new JsonqlValidationError('[getMutationArgs] Payload is malformed!', payload)\n}\n","// export\nimport {\n checkIsObject,\n notEmpty,\n checkIsAny,\n checkIsString,\n checkIsBoolean,\n checkIsNumber,\n checkIsArray\n} from './src'\n// PIA syntax\nexport const isObject = checkIsObject;\nexport const isAny = checkIsAny;\nexport const isString = checkIsString;\nexport const isBoolean = checkIsBoolean;\nexport const isNumber = checkIsNumber;\nexport const isArray = checkIsArray;\nexport const isNotEmpty = notEmpty;\n\nimport * as validator from './src/validator'\n\nexport const normalizeArgs = validator.normalizeArgs;\nexport const validateSync = validator.validateSync;\nexport const validateAsync = validator.validateAsync;\n\n// configuration checking\n\nimport * as jsonqlOptions from './src/options'\n\nexport const JSONQL_PARAMS_VALIDATOR_INFO = jsonqlOptions.JSONQL_PARAMS_VALIDATOR_INFO;\n\nexport const createConfig = jsonqlOptions.createConfig;\nexport const constructConfig = jsonqlOptions.constructConfigFn;\n\nexport const checkConfigAsync = jsonqlOptions.checkConfigAsync(validator.validateSync)\nexport const checkConfig = jsonqlOptions.checkConfig(validator.validateSync)\n\nimport isInArray from './src/is-in-array'\n\nexport const inArray = isInArray;\n\nimport checkKeyInObject from './src/check-key-in-object'\n\nexport const isKeyInObject = checkKeyInObject;\n\nimport checkIsContract from './src/check-is-contract'\n\nexport const isContract = checkIsContract;\n\n// add in v1.3.0\n\nimport * as paramsApi from './src/params-api'\n\nexport const createQuery = paramsApi.createQuery;\nexport const createQueryStr = paramsApi.createQueryStr;\nexport const createMutation = paramsApi.createMutation;\nexport const createMutationStr = paramsApi.createMutationStr;\nexport const getQueryFromArgs = paramsApi.getQueryFromArgs;\nexport const getQueryFromPayload = paramsApi.getQueryFromPayload;\nexport const getMutationFromArgs = paramsApi.getMutationFromArgs;\nexport const getMutationFromPayload = paramsApi.getMutationFromPayload;\nexport const getNameFromPayload = paramsApi.getNameFromPayload;\n","// This is ported back from ws-server and it will get use in the server / client side\nimport { isKeyInObject } from 'jsonql-params-validator'\n\nfunction extractSocketPart(contract) {\n if (isKeyInObject(contract, 'socket')) {\n return contract.socket;\n }\n return contract;\n}\n\n/**\n * @BUG we should check the socket part instead of expect the downstream to read the menu!\n * We only need this when the enableAuth is true otherwise there is only one namespace\n * @param {object} contract the socket part of the contract file\n * @return {object} 1. remap the contract using the namespace --> resolvers\n * 2. the size of the object (1 all private, 2 mixed public with private)\n * 3. which namespace is public\n */\nexport default function groupByNamespace(contract) {\n let socket = extractSocketPart(contract)\n\n let nspSet = {};\n let size = 0;\n let publicNamespace;\n for (let resolverName in socket) {\n let params = socket[resolverName];\n let { namespace } = params;\n if (namespace) {\n if (!nspSet[namespace]) {\n ++size;\n nspSet[namespace] = {};\n }\n nspSet[namespace][resolverName] = params;\n if (!publicNamespace) {\n if (params.public) {\n publicNamespace = namespace;\n }\n }\n }\n }\n return { size, nspSet, publicNamespace }\n}\n","// This is ported back from ws-client\n// the idea if from https://decembersoft.com/posts/promises-in-serial-with-array-reduce/\n/**\n * previously we already make sure the order of the namespaces\n * and attach the auth client to it\n * @param {array} promises array of unresolved promises\n * @return {object} promise resolved with the array of promises resolved results\n */\nexport default function chainPromises(promises) {\n return promises.reduce((promiseChain, currentTask) => (\n promiseChain.then(chainResults => (\n currentTask.then(currentResult => (\n [...chainResults, currentResult]\n ))\n ))\n ), Promise.resolve([]))\n}\n","/**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\nfunction InvalidCharacterError(message) {\n this.message = message;\n}\n\nInvalidCharacterError.prototype = new Error();\nInvalidCharacterError.prototype.name = 'InvalidCharacterError';\n\nfunction polyfill (input) {\n var str = String(input).replace(/=+$/, '');\n if (str.length % 4 == 1) {\n throw new InvalidCharacterError(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = '';\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n\nmodule.exports = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill;\n","// ws client using native WebSocket\nimport { JsonqlValidationError } from 'jsonql-errors';\n\nexport default function getWS() {\n switch(true) {\n case (typeof WebSocket !== 'undefined'):\n return WebSocket;\n case (typeof MozWebSocket !== 'undefined'):\n return MozWebSocket;\n // case (typeof global !== 'undefined'):\n // return global.WebSocket || global.MozWebSocket;\n case (typeof window !== 'undefined'):\n return window.WebSocket || window.MozWebSocket;\n // case (typeof self !== 'undefined'):\n // return self.WebSocket || self.MozWebSocket;\n default:\n throw new JsonqlValidationError('WebSocket is NOT SUPPORTED!')\n }\n}\n","// constants\n\nimport {\n EMIT_REPLY_TYPE,\n JS_WS_SOCKET_IO_NAME,\n JS_WS_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME\n} from 'jsonql-constants'\n\nconst SOCKET_IO = JS_WS_SOCKET_IO_NAME;\nconst WS = JS_WS_NAME;\n\nconst AVAILABLE_SERVERS = [SOCKET_IO, WS]\n\nconst SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!';\n\nconst SERVER_NOT_SUPPORT_ERR = 'is not supported server name!';\n\nconst MISSING_PROP_ERR = 'Missing property in contract!';\n\nconst UNKNOWN_CLIENT_ERR = 'Unknown client type!';\n\nconst EMIT_EVT = EMIT_REPLY_TYPE;\n\nconst NAMESPACE_KEY = 'namespaceMap';\n\nconst UNKNOWN_RESULT = 'UKNNOWN RESULT!';\n\nconst NOT_ALLOW_OP = 'This operation is not allow!';\n\nconst MY_NAMESPACE = 'myNamespace'\n\nexport {\n SOCKET_IO,\n WS,\n AVAILABLE_SERVERS,\n SOCKET_NOT_DEFINE_ERR,\n SERVER_NOT_SUPPORT_ERR,\n MISSING_PROP_ERR,\n UNKNOWN_CLIENT_ERR,\n EMIT_EVT,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n NAMESPACE_KEY,\n UNKNOWN_RESULT,\n NOT_ALLOW_OP,\n MY_NAMESPACE\n}\n","// generate the web socket connect client for browser\nimport {\n socketIoRoundtripLogin,\n socketIoClientAsync,\n socketIoHandshakeLogin,\n wsAuthClient,\n wsClient\n} from 'jsonql-jwt'\n\nimport { isString } from 'jsonql-params-validator'\nimport { JsonqlError } from 'jsonql-errors'\nimport { SOCKET_IO, WS } from './constants'\n// import { IO_ROUNDTRIP_LOGIN, IO_HANDSHAKE_LOGIN } from 'jsonql-constants'\nimport getDebug from './get-debug'\nconst debug = getDebug('client-generator')\n\n/**\n * create the web socket client\n * @param {object} payload passing\n * @return {object} just mutate it then pass it on\n */\nexport default function clientGenerator({opts, nspMap, ee}) {\n switch (opts.serverType) {\n case SOCKET_IO:\n opts.nspClient = (...args) => (\n Reflect.apply(socketIoClientAsync, null, [io, ...args])\n )\n if (isString(opts.useJwt)) {\n opts.nspAuthClient = (...args) => (\n Reflect.apply(socketIoRoundtripLogin, null, [io, ...args])\n )\n } else {\n opts.nspAuthClient = (...args) => (\n Reflect.apply(socketIoHandshakeLogin, null, [io, ...args])\n )\n }\n break;\n case WS:\n opts.nspClient = wsClient;\n opts.nspAuthClient = wsAuthClient;\n break;\n default:\n throw new JsonqlError(`Unknown serverType: ${opts.serverType}`)\n }\n return {opts, nspMap, ee}\n}\n","// since both the ws and io version are\n// pre-defined in the client-generator\n// and this one will have the same parameters\n// and the callback is identical\nimport getDebug from './get-debug'\nconst debugFn = getDebug('create-nsp-client')\n/**\n * wrapper method to create a nsp without login\n * @param {string|boolean} namespace namespace url could be false\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nconst nspClient = (namespace, opts) => {\n const { wssPath, wsOptions, hostname } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return opts.nspClient(url, wsOptions)\n}\n\n/**\n * wrapper method to create a nsp with token auth\n * @param {string} namespace namespace url\n * @param {object} opts configuration\n * @return {object} ws client instance\n */\nconst nspAuthClient = (namespace, opts) => {\n const { wssPath, token, wsOptions, hostname } = opts;\n const url = namespace ? [hostname, namespace].join('/') : wssPath;\n return opts.nspAuthClient(url, token, wsOptions)\n}\n\nexport {\n nspClient,\n nspAuthClient\n}\n","/**\n * generate a 32bit hash based on the function.toString()\n * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery\n * @param {string} s the converted to string function\n * @return {string} the hashed function string\n */\nexport default function hashCode(s) {\n\treturn s.split(\"\").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)\n}\n","// making all the functionality on it's own\n// import { WatchClass } from './watch'\n\nexport default class SuspendClass {\n\n constructor() {\n // suspend, release and queue\n this.__suspend__ = null;\n this.queueStore = new Set()\n /*\n this.watch('suspend', function(value, prop, oldValue) {\n this.logger(`${prop} set from ${oldValue} to ${value}`)\n // it means it set the suspend = true then release it\n if (oldValue === true && value === false) {\n // we want this happen after the return happens\n setTimeout(() => {\n this.release()\n }, 1)\n }\n return value; // we need to return the value to store it\n })\n */\n }\n\n /**\n * setter to set the suspend and check if it's boolean value\n * @param {boolean} value to trigger\n */\n set $suspend(value) {\n if (typeof value === 'boolean') {\n const lastValue = this.__suspend__;\n this.__suspend__ = value;\n this.logger('($suspend)', `Change from ${lastValue} --> ${value}`)\n if (lastValue === true && value === false) {\n setTimeout(() => {\n this.release()\n }, 1)\n }\n } else {\n throw new Error(`$suspend only accept Boolean value!`)\n }\n }\n\n /**\n * queuing call up when it's in suspend mode\n * @param {any} value\n * @return {Boolean} true when added or false when it's not\n */\n $queue(...args) {\n if (this.__suspend__ === true) {\n this.logger('($queue)', 'added to $queue', args)\n // there shouldn't be any duplicate ...\n this.queueStore.add(args)\n }\n return this.__suspend__;\n }\n\n /**\n * a getter to get all the store queue\n * @return {array} Set turn into Array before return\n */\n get $queues() {\n let size = this.queueStore.size;\n this.logger('($queues)', `size: ${size}`)\n if (size > 0) {\n return Array.from(this.queueStore)\n }\n return []\n }\n\n /**\n * Release the queue\n * @return {int} size if any\n */\n release() {\n let size = this.queueStore.size\n this.logger('(release)', `Release was called ${size}`)\n if (size > 0) {\n const queue = Array.from(this.queueStore)\n this.queueStore.clear()\n this.logger('queue', queue)\n queue.forEach(args => {\n this.logger(args)\n Reflect.apply(this.$trigger, this, args)\n })\n this.logger(`Release size ${this.queueStore.size}`)\n }\n }\n}\n","// break up the main file because its getting way too long\nimport {\n NB_EVENT_SERVICE_PRIVATE_STORE,\n NB_EVENT_SERVICE_PRIVATE_LAZY\n} from './store'\nimport genHaskKey from './hash-code'\nimport SuspendClass from './suspend'\n\nexport default class NbEventServiceBase extends SuspendClass {\n\n constructor(config = {}) {\n super()\n if (config.logger && typeof config.logger === 'function') {\n this.logger = config.logger;\n }\n this.keep = config.keep;\n // for the $done setter\n this.result = config.keep ? [] : null;\n // we need to init the store first otherwise it could be a lot of checking later\n this.normalStore = new Map()\n this.lazyStore = new Map()\n }\n\n /**\n * validate the event name(s)\n * @param {string[]} evt event name\n * @return {boolean} true when OK\n */\n validateEvt(...evt) {\n evt.forEach(e => {\n if (typeof e !== 'string') {\n this.logger('(validateEvt)', e)\n throw new Error(`event name must be string type!`)\n }\n })\n return true;\n }\n\n /**\n * Simple quick check on the two main parameters\n * @param {string} evt event name\n * @param {function} callback function to call\n * @return {boolean} true when OK\n */\n validate(evt, callback) {\n if (this.validateEvt(evt)) {\n if (typeof callback === 'function') {\n return true;\n }\n }\n throw new Error(`callback required to be function type!`)\n }\n\n /**\n * Check if this type is correct or not added in V1.5.0\n * @param {string} type for checking\n * @return {boolean} true on OK\n */\n validateType(type) {\n const types = ['on', 'only', 'once', 'onlyOnce']\n return !!types.filter(t => type === t).length;\n }\n\n /**\n * Run the callback\n * @param {function} callback function to execute\n * @param {array} payload for callback\n * @param {object} ctx context or null\n * @return {void} the result store in $done\n */\n run(callback, payload, ctx) {\n this.logger('(run)', callback, payload, ctx)\n this.$done = Reflect.apply(callback, ctx, this.toArray(payload))\n }\n\n /**\n * Take the content out and remove it from store id by the name\n * @param {string} evt event name\n * @param {string} [storeName = lazyStore] name of store\n * @return {object|boolean} content or false on not found\n */\n takeFromStore(evt, storeName = 'lazyStore') {\n let store = this[storeName]; // it could be empty at this point\n if (store) {\n this.logger('(takeFromStore)', storeName, store)\n if (store.has(evt)) {\n let content = store.get(evt)\n this.logger('(takeFromStore)', `has ${evt}`, content)\n store.delete(evt)\n return content;\n }\n return false;\n }\n throw new Error(`${storeName} is not supported!`)\n }\n\n /**\n * The add to store step is similar so make it generic for resuse\n * @param {object} store which store to use\n * @param {string} evt event name\n * @param {spread} args because the lazy store and normal store store different things\n * @return {array} store and the size of the store\n */\n addToStore(store, evt, ...args) {\n let fnSet;\n if (store.has(evt)) {\n this.logger('(addToStore)', `${evt} existed`)\n fnSet = store.get(evt)\n } else {\n this.logger('(addToStore)', `create new Set for ${evt}`)\n // this is new\n fnSet = new Set()\n }\n // lazy only store 2 items - this is not the case in V1.6.0 anymore\n // we need to check the first parameter is string or not\n if (args.length > 2) {\n if (Array.isArray(args[0])) { // lazy store\n // check if this type of this event already register in the lazy store\n let [,,t] = args;\n if (!this.checkTypeInLazyStore(evt, t)) {\n fnSet.add(args)\n }\n } else {\n if (!this.checkContentExist(args, fnSet)) {\n this.logger('(addToStore)', `insert new`, args)\n fnSet.add(args)\n }\n }\n } else { // add straight to lazy store\n fnSet.add(args)\n }\n store.set(evt, fnSet)\n return [store, fnSet.size]\n }\n\n /**\n * @param {array} args for compare\n * @param {object} fnSet A Set to search from\n * @return {boolean} true on exist\n */\n checkContentExist(args, fnSet) {\n let list = Array.from(fnSet)\n return !!list.filter(l => {\n let [hash,] = l;\n if (hash === args[0]) {\n return true;\n }\n return false;\n }).length;\n }\n\n /**\n * get the existing type to make sure no mix type add to the same store\n * @param {string} evtName event name\n * @param {string} type the type to check\n * @return {boolean} true you can add, false then you can't add this type\n */\n checkTypeInStore(evtName, type) {\n this.validateEvt(evtName, type)\n let all = this.$get(evtName, true)\n if (all === false) {\n // pristine it means you can add\n return true;\n }\n // it should only have ONE type in ONE event store\n return !all.filter(list => {\n let [ ,,,t ] = list;\n return type !== t;\n }).length;\n }\n\n /**\n * This is checking just the lazy store because the structure is different\n * therefore we need to use a new method to check it\n */\n checkTypeInLazyStore(evtName, type) {\n this.validateEvt(evtName, type)\n let store = this.lazyStore.get(evtName)\n this.logger('(checkTypeInLazyStore)', store)\n if (store) {\n return !!Array\n .from(store)\n .filter(l => {\n let [,,t] = l;\n return t !== type;\n }).length\n }\n return false;\n }\n\n /**\n * wrapper to re-use the addToStore,\n * V1.3.0 add extra check to see if this type can add to this evt\n * @param {string} evt event name\n * @param {string} type on or once\n * @param {function} callback function\n * @param {object} context the context the function execute in or null\n * @return {number} size of the store\n */\n addToNormalStore(evt, type, callback, context = null) {\n this.logger('(addToNormalStore)', evt, type, 'try to add to normal store')\n // @TODO we need to check the existing store for the type first!\n if (this.checkTypeInStore(evt, type)) {\n this.logger('(addToNormalStore)', `${type} can add to ${evt} normal store`)\n let key = this.hashFnToKey(callback)\n let args = [this.normalStore, evt, key, callback, context, type]\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.normalStore = _store;\n return size;\n }\n return false;\n }\n\n /**\n * Add to lazy store this get calls when the callback is not register yet\n * so we only get a payload object or even nothing\n * @param {string} evt event name\n * @param {array} payload of arguments or empty if there is none\n * @param {object} [context=null] the context the callback execute in\n * @param {string} [type=false] register a type so no other type can add to this evt\n * @return {number} size of the store\n */\n addToLazyStore(evt, payload = [], context = null, type = false) {\n // this is add in V1.6.0\n // when there is type then we will need to check if this already added in lazy store\n // and no other type can add to this lazy store\n let args = [this.lazyStore, evt, this.toArray(payload), context]\n if (type) {\n args.push(type)\n }\n let [_store, size] = Reflect.apply(this.addToStore, this, args)\n this.lazyStore = _store;\n return size;\n }\n\n /**\n * make sure we store the argument correctly\n * @param {*} arg could be array\n * @return {array} make sured\n */\n toArray(arg) {\n return Array.isArray(arg) ? arg : [arg];\n }\n\n /**\n * setter to store the Set in private\n * @param {object} obj a Set\n */\n set normalStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj)\n }\n\n /**\n * @return {object} Set object\n */\n get normalStore() {\n return NB_EVENT_SERVICE_PRIVATE_STORE.get(this)\n }\n\n /**\n * setter to store the Set in lazy store\n * @param {object} obj a Set\n */\n set lazyStore(obj) {\n NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj)\n }\n\n /**\n * @return {object} the lazy store Set\n */\n get lazyStore() {\n return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this)\n }\n\n /**\n * generate a hashKey to identify the function call\n * The build-in store some how could store the same values!\n * @param {function} fn the converted to string function\n * @return {string} hashKey\n */\n hashFnToKey(fn) {\n return genHaskKey(fn.toString()) + '';\n }\n}\n","// The top level\nimport NbStoreService from './store-service'\n// export\nexport default class EventService extends NbStoreService {\n /**\n * class constructor\n */\n constructor(config = {}) {\n super(config)\n }\n\n /**\n * logger function for overwrite\n */\n logger() {}\n\n //////////////////////////\n // PUBLIC METHODS //\n //////////////////////////\n\n /**\n * Register your evt handler, note we don't check the type here,\n * we expect you to be sensible and know what you are doing.\n * @param {string} evt name of event\n * @param {function} callback bind method --> if it's array or not\n * @param {object} [context=null] to execute this call in\n * @return {number} the size of the store\n */\n $on(evt , callback , context = null) {\n const type = 'on';\n this.validate(evt, callback)\n // first need to check if this evt is in lazy store\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register first then call later\n if (lazyStoreContent === false) {\n this.logger('($on)', `${evt} callback is not in lazy store`)\n // @TODO we need to check if there was other listener to this\n // event and are they the same type then we could solve that\n // register the different type to the same event name\n\n return this.addToNormalStore(evt, type, callback, context)\n }\n this.logger('($on)', `${evt} found in lazy store`)\n // this is when they call $trigger before register this callback\n let size = 0;\n lazyStoreContent.forEach(content => {\n let [ payload, ctx, t ] = content;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.run(callback, payload, context || ctx)\n size += this.addToNormalStore(evt, type, callback, context || ctx)\n })\n return size;\n }\n\n /**\n * once only registered it once, there is no overwrite option here\n * @NOTE change in v1.3.0 $once can add multiple listeners\n * but once the event fired, it will remove this event (see $only)\n * @param {string} evt name\n * @param {function} callback to execute\n * @param {object} [context=null] the handler execute in\n * @return {boolean} result\n */\n $once(evt , callback , context = null) {\n this.validate(evt, callback)\n const type = 'once';\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (lazyStoreContent === false) {\n this.logger('($once)', `${evt} not in the lazy store`)\n // v1.3.0 $once now allow to add multiple listeners\n return this.addToNormalStore(evt, type, callback, context)\n } else {\n // now this is the tricky bit\n // there is a potential bug here that cause by the developer\n // if they call $trigger first, the lazy won't know it's a once call\n // so if in the middle they register any call with the same evt name\n // then this $once call will be fucked - add this to the documentation\n this.logger('($once)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n }\n\n /**\n * This one event can only bind one callbackback\n * @param {string} evt event name\n * @param {function} callback event handler\n * @param {object} [context=null] the context the event handler execute in\n * @return {boolean} true bind for first time, false already existed\n */\n $only(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'only';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($only)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($only)', `${evt} found data in lazy store to execute`)\n const list = Array.from(lazyStoreContent)\n // $only allow to trigger this multiple time on the single handler\n list.forEach( l => {\n const [ payload, ctx, t ] = l;\n if (t && t !== type) {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.run(callback, payload, context || ctx)\n })\n }\n return added;\n }\n\n /**\n * $only + $once this is because I found a very subtile bug when we pass a\n * resolver, rejecter - and it never fire because that's OLD adeed in v1.4.0\n * @param {string} evt event name\n * @param {function} callback to call later\n * @param {object} [context=null] exeucte context\n * @return {void}\n */\n $onlyOnce(evt, callback, context = null) {\n this.validate(evt, callback)\n const type = 'onlyOnce';\n let added = false;\n let lazyStoreContent = this.takeFromStore(evt)\n // this is normal register before call $trigger\n let nStore = this.normalStore;\n if (!nStore.has(evt)) {\n this.logger(`($onlyOnce)`, `${evt} add to store`)\n added = this.addToNormalStore(evt, type, callback, context)\n }\n if (lazyStoreContent !== false) {\n // there are data store in lazy store\n this.logger('($onlyOnce)', lazyStoreContent)\n const list = Array.from(lazyStoreContent)\n // should never have more than 1\n const [ payload, ctx, t ] = list[0]\n if (t && t !== 'onlyOnce') {\n throw new Error(`You are trying to register an event already been taken by other type: ${t}`)\n }\n this.run(callback, payload, context || ctx)\n // remove this evt from store\n this.$off(evt)\n }\n return added;\n }\n\n /**\n * This is a shorthand of $off + $on added in V1.5.0\n * @param {string} evt event name\n * @param {function} callback to exeucte\n * @param {object} [context = null] or pass a string as type\n * @param {string} [type=on] what type of method to replace\n * @return {}\n */\n $replace(evt, callback, context = null, type = 'on') {\n if (this.validateType(type)) {\n this.$off(evt)\n let method = this['$' + type]\n return Reflect.apply(method, this, [evt, callback, context])\n }\n throw new Error(`${type} is not supported!`)\n }\n\n /**\n * trigger the event\n * @param {string} evt name NOT allow array anymore!\n * @param {mixed} [payload = []] pass to fn\n * @param {object|string} [context = null] overwrite what stored\n * @param {string} [type=false] if pass this then we need to add type to store too\n * @return {number} if it has been execute how many times\n */\n $trigger(evt , payload = [] , context = null, type = false) {\n this.validateEvt(evt)\n let found = 0;\n // first check the normal store\n let nStore = this.normalStore;\n this.logger('($trigger)', 'normalStore', nStore)\n if (nStore.has(evt)) {\n // @1.8.0 to add the suspend queue\n let added = this.$queue(evt, payload, context, type)\n this.logger('($trigger)', evt, 'found; add to queue: ', added)\n if (added === true) {\n return false; // not executed\n }\n let nSet = Array.from(nStore.get(evt))\n let ctn = nSet.length;\n let hasOnce = false;\n let hasOnly = false;\n for (let i=0; i < ctn; ++i) {\n ++found;\n // this.logger('found', found)\n let [ _, callback, ctx, type ] = nSet[i]\n this.run(callback, payload, context || ctx)\n if (type === 'once' || type === 'onlyOnce') {\n hasOnce = true;\n }\n }\n if (hasOnce) {\n nStore.delete(evt)\n }\n return found;\n }\n // now this is not register yet\n this.addToLazyStore(evt, payload, context, type)\n return found;\n }\n\n /**\n * this is an alias to the $trigger\n * @NOTE breaking change in V1.6.0 we swap the parameter around\n * @param {string} evt event name\n * @param {*} params pass to the callback\n * @param {string} type of call\n * @param {object} context what context callback execute in\n * @return {*} from $trigger\n */\n $call(evt, params, type = false, context = null) {\n let args = [evt, params]\n args.push(context, type)\n return Reflect.apply(this.$trigger, this, args)\n }\n\n /**\n * remove the evt from all the stores\n * @param {string} evt name\n * @return {boolean} true actually delete something\n */\n $off(evt) {\n this.validateEvt(evt)\n let stores = [ this.lazyStore, this.normalStore ]\n let found = false;\n stores.forEach(store => {\n if (store.has(evt)) {\n found = true;\n store.delete(evt)\n }\n })\n return found;\n }\n\n /**\n * return all the listener from the event\n * @param {string} evtName event name\n * @param {boolean} [full=false] if true then return the entire content\n * @return {array|boolean} listerner(s) or false when not found\n */\n $get(evt, full = false) {\n this.validateEvt(evt)\n let store = this.normalStore;\n if (store.has(evt)) {\n return Array\n .from(store.get(evt))\n .map( l => {\n if (full) {\n return l;\n }\n let [key, callback, ] = l;\n return callback;\n })\n }\n return false;\n }\n\n /**\n * store the return result from the run\n * @param {*} value whatever return from callback\n */\n set $done(value) {\n this.logger('($done)', 'value: ', value)\n if (this.keep) {\n this.result.push(value)\n } else {\n this.result = value;\n }\n }\n\n /**\n * @TODO is there any real use with the keep prop?\n * getter for $done\n * @return {*} whatever last store result\n */\n get $done() {\n if (this.keep) {\n this.logger('(get $done)', this.result)\n return this.result[this.result.length - 1]\n }\n return this.result;\n }\n\n\n}\n","// default\nimport NBEventService from './src/event-service'\n\nexport default NBEventService\n","// mapping the resolver to their respective nsp\n\nimport { JSONQL_PATH } from 'jsonql-constants'\nimport { groupByNamespace } from 'jsonql-jwt'\nimport { JsonqlResolverNotFoundError } from 'jsonql-errors'\n\nimport { MISSING_PROP_ERR } from './constants'\nimport getDebug from './get-debug'\nconst debug = getDebug('process-contract')\n\n/**\n * Just make sure the object contain what we are looking for\n * @param {object} opts configuration from checkOptions\n * @return {object} the target content\n */\nconst getResolverList = contract => {\n if (contract) {\n const { socket } = contract;\n if (socket) {\n return socket;\n }\n }\n throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR)\n}\n\n/**\n * process the contract first\n * @param {object} opts configuration\n * @return {object} sorted list\n */\nexport default function processContract(opts) {\n const { contract, enableAuth } = opts;\n if (enableAuth) {\n return groupByNamespace(contract)\n }\n return {\n nspSet: { [JSONQL_PATH]: getResolverList(contract) },\n publicNamespace: JSONQL_PATH,\n size: 1 // this prop is pretty meaningless now\n }\n}\n","// export the util methods\nimport { QUERY_ARG_NAME, JS_WS_SOCKET_IO_NAME } from 'jsonql-constants'\nimport getNamespaceInOrder from './get-namespace-in-order'\nimport checkOptions from './check-options'\nimport ee from './ee'\nimport * as constants from './constants'\nimport getDebug from './get-debug'\n\nimport processContract from './process-contract'\nimport { isArray } from 'jsonql-params-validator'\n\nconst toArray = (arg) => isArray(arg) ? arg : [arg];\n\n/**\n * very simple tool to create the event name\n * @param {string} [...args] spread\n * @return {string} join by _\n */\nconst createEvt = (...args) => args.join('_')\n\n/**\n * Unbind the event\n * @param {object} ee EventEmitter\n * @param {string} namespace\n * @return {void}\n */\nconst clearMainEmitEvt = (ee, namespace) => {\n let nsps = isArray(namespace) ? namespace : [namespace]\n nsps.forEach(n => {\n ee.$off(createEvt(n, constants.EMIT_EVT))\n })\n}\n\n/**\n * @param {*} args arguments to send\n *@return {object} formatted payload\n */\nconst formatPayload = (args) => (\n { [QUERY_ARG_NAME]: args }\n)\n\n/**\n * @param {object} nsps namespace as key\n * @param {string} type of server\n */\nconst disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => {\n try {\n const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate';\n for (let namespace in nsps) {\n let nsp = nsps[namespace]\n if (nsp && nsp[method]) {\n Reflect.apply(nsp[method], null, [])\n }\n }\n } catch(e) {\n // socket.io throw a this.destroy of undefined?\n console.error('disconnect', e)\n }\n}\n\n\nexport {\n getNamespaceInOrder,\n createEvt,\n clearMainEmitEvt,\n checkOptions,\n ee,\n constants,\n getDebug,\n processContract,\n toArray,\n formatPayload,\n disconnect\n}\n","// @TODO port what is in the ws-main-handler\n// because all the client side call are via the ee\n// and that makes it re-usable between different client setup\nimport {\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n EMIT_EVT,\n SOCKET_IO,\n WS\n} from './utils/constants'\nimport {\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n NOT_LOGIN_ERR_MSG,\n ERROR_PROP_NAME\n} from 'jsonql-constants'\n\nimport { getDebug, createEvt, clearMainEmitEvt } from './utils'\nimport triggerNamespacesOnError from './utils/trigger-namespaces-on-error'\nconst debugFn = getDebug('client-event-handler')\n\n/**\n * A fake ee handler\n * @param {string} namespace nsp\n * @param {object} ee EventEmitter\n * @return {void}\n */\nconst notLoginWsHandler = (namespace, ee) => {\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function(resolverName, args) {\n debugFn('noLoginHandler hijack the ws call', namespace, resolverName, args)\n let error = {\n message: NOT_LOGIN_ERR_MSG\n }\n // It should just throw error here and should not call the result\n // because that's channel for handling normal event not the fake one\n ee.$call(createEvt(namespace, resolverName, ERROR_PROP_NAME), [error])\n // also trigger the result handler, but wrap inside the error key\n ee.$call(createEvt(namespace, resolverName, RESULT_PROP_NAME), [{ error }])\n }\n )\n}\n\n/**\n * centralize all the comm in one place\n * @param {object} opts configuration\n * @param {array} namespaces namespace(s)\n * @param {object} ee Event Emitter instance\n * @param {function} bindWsHandler binding the ee to ws\n * @param {array} namespaces array of namespace available\n * @param {object} nsps namespaced nsp\n * @return {void} nothing\n */\nexport default function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) {\n // loop\n // @BUG for io this has to be in order the one with auth need to get call first\n // The order of login is very import we need to run a waterfall here to make sure\n // one is execute then the other\n namespaces.forEach(namespace => {\n if (nsps[namespace]) {\n debugFn('call bindWsHandler', namespace)\n let args = [namespace, nsps[namespace], ee]\n if (opts.serverType === SOCKET_IO) {\n let { nspSet } = nspMap;\n args.push(nspSet[namespace])\n args.push(opts)\n }\n Reflect.apply(bindWsHandler, null, args)\n } else {\n // a dummy placeholder\n notLoginWsHandler(namespace, ee)\n }\n })\n // this will be available regardless enableAuth\n // because the server can log the client out\n ee.$on(LOGOUT_EVENT_NAME, function() {\n debugFn('LOGOUT_EVENT_NAME')\n // disconnect(nsps, opts.serverType)\n // we need to issue error to all the namespace onError handler\n triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME)\n // rebind all of the handler to the fake one\n namespaces.forEach( namespace => {\n clearMainEmitEvt(ee, namespace)\n // clear out the nsp\n nsps[namespace] = false;\n // add a NOT LOGIN error if call\n notLoginWsHandler(namespace, ee)\n })\n })\n}\n","// take the ws reply data for use\nimport { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants'\nimport { isString, isKeyInObject } from 'jsonql-params-validator'\nimport { JsonqlError, clientErrorsHandler } from 'jsonql-errors'\n\nimport getDebug from '../utils/get-debug'\nconst debugFn = getDebug('extract-ws-payload')\n\nconst keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]\n\n/**\n * @param {object} payload should be string when reply but could be transformed\n * @return {boolean} true is OK\n */\nconst isWsReply = payload => {\n const { data } = payload;\n if (data) {\n let result = keys.filter(key => isKeyInObject(data, key))\n return (result.length === keys.length) ? data : false;\n }\n return false;\n}\n\n/**\n * @param {object} payload This is the entire ws Event Object\n * @return {object} false on failed\n */\nconst extractWsPayload = payload => {\n const { data } = payload;\n let json = isString(data) ? JSON.parse(data) : data;\n // debugFn('extractWsPayload', json)\n let fdata;\n if ((fdata = isWsReply(json)) !== false) {\n return {\n resolverName: fdata[WS_EVT_NAME],\n data: fdata[WS_DATA_NAME],\n type: fdata[WS_REPLY_TYPE]\n };\n }\n throw new JsonqlError('payload can not be decoded', payload)\n}\n// export it\nexport default extractWsPayload\n","// the WebSocket main handler\nimport {\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n EMIT_EVT\n} from '../utils/constants'\nimport {\n ERROR_PROP_NAME,\n LOGIN_EVENT_NAME,\n LOGOUT_EVENT_NAME,\n ACKNOWLEDGE_REPLY_TYPE,\n EMIT_REPLY_TYPE,\n ERROR_TYPE,\n READY_PROP_NAME\n} from 'jsonql-constants'\n\nimport extractWsPayload from './extract-ws-payload'\nimport { createQueryStr } from 'jsonql-params-validator'\n\nimport { getDebug, createEvt } from '../utils'\nconst debugFn = getDebug('ws-main-handler')\n\n/**\n * under extremely circumstances we might not even have a resolverName, then\n * we issue a global error for the developer to catch it\n * @param {object} ee event emitter\n * @param {string} namespace nsp\n * @param {string} resolverName resolver\n * @param {object} json decoded payload or error object\n */\nconst errorTypeHandler = (ee, namespace, resolverName, json) => {\n let evt = [namespace]\n if (resolverName) {\n debugFn(`a global error on ${namespace}`)\n evt.push(resolverName)\n }\n evt.push(ERROR_PROP_NAME)\n let evtName = Reflect.apply(createEvt, null, evt)\n // test if there is a data field\n let payload = json.data || json;\n ee.$trigger(evtName, [payload])\n}\n\n/**\n * Binding the even to socket normally\n * @param {string} namespace\n * @param {object} ws the nsp\n * @param {object} ee EventEmitter\n * @return {object} promise resolve after the onopen event\n */\nexport default function wsMainHandlerAction(namespace, ws, ee) {\n // send\n ws.onopen = function() {\n // we just call the onReady\n ee.$call(READY_PROP_NAME, namespace)\n // add listener\n ee.$only(\n createEvt(namespace, EMIT_EVT),\n function(resolverName, args) {\n debugFn('calling server', resolverName, args)\n ws.send(\n createQueryStr(resolverName, args)\n )\n }\n )\n }\n\n // reply\n ws.onmessage = function(payload) {\n try {\n const json = extractWsPayload(payload)\n debugFn('Hear from server', json)\n const { resolverName, type } = json;\n switch (type) {\n case EMIT_REPLY_TYPE:\n let r = ee.$trigger(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), [json])\n debugFn(MESSAGE_PROP_NAME, r)\n break;\n case ACKNOWLEDGE_REPLY_TYPE:\n debugFn(RESULT_PROP_NAME, json)\n let x = ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [json])\n debugFn('onResult add to event?', x)\n break;\n case ERROR_TYPE:\n // this is handled error and we won't throw it\n // we need to extract the error from json\n errorTypeHandler(ee, namespace, resolverName, json)\n break;\n // @TODO there should be an error type instead of roll into the other two types? TBC\n default:\n // if this happen then we should throw it and halt the operation all together\n debugFn('Unhandled event!', json)\n errorTypeHandler(ee, namespace, resolverName, json)\n // let error = {error: {'message': 'Unhandled event!', type}};\n // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error])\n }\n } catch(e) {\n errorTypeHandler(ee, namespace, false, e)\n }\n }\n // when the server close the connection\n ws.onclose = function() {\n debugFn('ws.onclose')\n // @TODO what to do with this\n // ee.$trigger(LOGOUT_EVENT_NAME, [namespace])\n }\n // listen to the LOGOUT_EVENT_NAME\n ee.$on(LOGOUT_EVENT_NAME, function close() {\n try {\n debugFn('terminate ws connection')\n ws.terminate()\n } catch(e) {\n debugFn('terminate ws error', e)\n }\n })\n}\n","// make this another standalone module\nimport { getNameFromPayload } from 'jsonql-params-validator'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants'\nimport { nspClient, nspAuthClient } from '../utils/create-nsp-client'\n// this become the cb\nimport clientEventHandler from '../client-event-handler'\nimport triggerNamespacesOnError from '../utils/trigger-namespaces-on-error'\n// move this up one level from client-event-handler\nimport wsMainHandler from './ws-main-handler'\nimport { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils'\nconst debugFn = getDebug('ws-create-client')\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let namespaces = [];\n let nsps = {};\n // first we need to binding all the events handler\n if (opts.enableAuth && opts.useJwt) {\n login = true; // just saying we need to listen to login event\n namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n nsps = namespaces.map((namespace, i) => {\n if (i === 0) {\n if (token) {\n opts.token = token;\n return {[namespace]: nspAuthClient(namespace, opts)}\n }\n return {[namespace]: false}\n }\n return {[namespace]: nspClient(namespace, opts)}\n }).reduce((first, next) => Object.assign(first, next), {})\n } else {\n let namespace = getNameFromPayload(nspSet)\n namespaces.push(namespace)\n // standard without login\n // the stock version should not have a namespace\n nsps[namespace] = nspClient(false, opts)\n }\n // return\n return { nsps, namespaces, login }\n}\n\n/**\n * create a ws client\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport default function createClient(opts, nspMap, ee) {\n // arguments that don't change\n let args = [opts, nspMap, ee, wsMainHandler]\n // now create the nsps\n let { nsps, namespaces, login } = createNsps(opts, nspMap, opts.token)\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n // setup listener\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function(token) {\n disconnect(nsps, JS_WS_NAME)\n // @TODO should we trigger error on this one?\n // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME)\n clearMainEmitEvt(ee, namespaces)\n debugFn('LOGIN_EVENT_NAME', token)\n let newNsps = createNsps(opts, nspMap, token)\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n }\n // return what input\n return { opts, nspMap, ee }\n}\n","// we only need to export one interface from now on\n\nimport createClient from './create-client'\n\nexport default createClient\n","// this will create the socket.io client\nimport { chainPromises } from 'jsonql-jwt'\nimport { getNameFromPayload, isString } from 'jsonql-params-validator'\nimport { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants'\n\nimport { nspClient, nspAuthClient } from '../utils/create-nsp-client'\nimport clientEventHandler from '../client-event-handler'\nimport ioMainHandler from './io-main-handler'\n\nimport { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils'\nconst debugFn = getDebug('io-create-client')\n\n// just to make it less ugly\nconst mapNsps = (nsps, namespaces) => nsps\n .map((nsp, i) => ({[namespaces[i]]: nsp}))\n .reduce((last, next) => Object.assign(last,next), {})\n\n/**\n * This one will run the create nsps in sequence and make sure\n * the auth one connect before we call the others\n * @param {object} opts configuration\n * @param {object} nspMap contract map\n * @param {string} token validation\n * @return {object} promise resolve with namespaces, nsps in same order array\n */\nconst createAuthNsps = function(opts, nspMap, token, namespaces) {\n let { publicNamespace } = nspMap;\n opts.token = token;\n let p1 = () => nspAuthClient(namespaces[0], opts)\n let p2 = () => nspClient(namespaces[1], opts)\n return chainPromises([p1(), p2()])\n .then(nsps => ({\n nsps: mapNsps(nsps, namespaces),\n namespaces,\n login: false\n }))\n}\n\n/**\n * Because the nsps can be throw away so it doesn't matter the scope\n * this will get reuse again\n * @param {object} opts configuration\n * @param {object} nspMap from contract\n * @param {string|null} token whether we have the token at run time\n * @return {object} nsps namespace with namespace as key\n */\nconst createNsps = function(opts, nspMap, token) {\n let { nspSet, publicNamespace } = nspMap;\n let login = false;\n let nsps = {}\n // first we need to binding all the events handler\n if (opts.enableAuth && opts.useJwt) {\n let namespaces = getNamespaceInOrder(nspSet, publicNamespace)\n debugFn('namespaces', namespaces)\n login = opts.useJwt; // just saying we need to listen to login event\n if (token) {\n debugFn('call createAuthNsps')\n return createAuthNsps(opts, nspMap, token, namespaces)\n }\n debugFn('init with a placeholder')\n return nspClient(publicNamespace, opts)\n .then(nsp => ({\n nsps: {\n [ publicNamespace ]: nsp,\n [ namespaces[0] ]: false\n },\n namespaces,\n login\n }))\n }\n // standard without login\n // the stock version should not have a namespace\n return nspClient(false, opts)\n .then(nsp => ({\n nsps: {[publicNamespace]: nsp},\n namespaces: [publicNamespace],\n login\n }))\n}\n\n\n\n/**\n * This is just copy of the ws version we need to figure\n * out how to deal with the roundtrip login later\n * @param {object} opts configuration\n * @param {object} nspMap namespace with resolvers\n * @param {object} ee EventEmitter to pass through\n * @return {object} what comes in what goes out\n */\nexport default function createClient(opts, nspMap, ee) {\n // arguments don't change\n let args = [opts, nspMap, ee, ioMainHandler]\n return createNsps(opts, nspMap, opts.token)\n .then( ({ nsps, namespaces, login }) => {\n // binding the listeners - and it will listen to LOGOUT event\n // to unbind itself, and the above call will bind it again\n Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps]))\n if (login) {\n ee.$only(LOGIN_EVENT_NAME, function(token) {\n // here we should disconnect all the previous nsps\n disconnect(nsps)\n // first trigger a LOGOUT event to unbind ee to ws\n // ee.$trigger(LOGOUT_EVENT_NAME) // <-- this seems to cause a lot of problems\n clearMainEmitEvt(ee, namespaces)\n debugFn('LOGIN_EVENT_NAME')\n createNsps(opts, nspMap, token)\n .then(newNsps => {\n // rebind it\n Reflect.apply(\n clientEventHandler,\n null,\n args.concat([newNsps.namespaces, newNsps.nsps])\n )\n })\n })\n }\n // return this will also works because the outter call are in promise chain\n return { opts, nspMap, ee }\n })\n}\n","// generator resolvers\n// this will be a mini client server architect\n// The reason is when the enableAuth setup - the private route\n// might not be validated, but we need the callable point is ready\n// therefore this part will always take the contract and generate\n// callable api for the developer to setup their front end\n// the only thing is - when they call they might get an error or\n// NOT_LOGIN_IN and they can react to this error accordingly\nimport {\n JsonqlResolverNotFoundError,\n JsonqlValidationError,\n JsonqlError,\n finalCatch\n} from 'jsonql-errors'\nimport {\n validateAsync,\n validateSync,\n isKeyInObject,\n isString\n} from 'jsonql-params-validator'\nimport {\n ERROR_TYPE,\n DATA_KEY,\n ERROR_KEY,\n ERROR_PROP_NAME,\n MESSAGE_PROP_NAME,\n RESULT_PROP_NAME,\n SEND_MSG_PROP_NAME,\n LOGIN_EVENT_NAME,\n READY_PROP_NAME,\n LOGOUT_EVENT_NAME\n} from 'jsonql-constants'\nimport { getDebug, constants, createEvt, toArray } from './utils'\nconst { EMIT_EVT, NOT_ALLOW_OP, UNKNOWN_RESULT, MY_NAMESPACE } = constants;\nconst debugFn = getDebug('generator')\n\n/**\n * prepare the methods\n * @param {object} opts configuration\n * @param {object} nspMap resolvers index by their namespace\n * @param {object} ee EventEmitter\n * @return {object} of resolvers\n * @public\n */\nexport default function generator(opts, nspMap, ee) {\n const obj = {};\n const { nspSet } = nspMap;\n for (let namespace in nspSet) {\n let list = nspSet[namespace]\n for (let resolverName in list) {\n let params = list[resolverName]\n let fn = createResolver(ee, namespace, resolverName, params)\n obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee)\n }\n }\n // add error handler\n createNamespaceErrorHandler(obj, ee, nspSet)\n // add onReady handler\n createOnReadyhandler(obj, ee, nspSet)\n // Auth related methods\n createAuthMethods(obj, ee, opts)\n // this is a helper method for the developer to know the namespace inside\n obj.getNsp = () => {\n return Object.keys(nspSet)\n }\n // output\n return obj;\n}\n\n/**\n * create the actual function to send message to server\n * @param {object} ee EventEmitter instance\n * @param {string} namespace this resolver end point\n * @param {string} resolverName name of resolver as event name\n * @param {object} params from contract\n * @return {function} resolver\n */\nfunction createResolver(ee, namespace, resolverName, params) {\n // note we pass the new withResult=true option\n return function(...args) {\n return validateAsync(args, params.params, true)\n .then( _args => actionCall(ee, namespace, resolverName, _args) )\n .catch(finalCatch)\n }\n}\n\n/**\n * just wrapper\n * @param {object} ee EventEmitter\n * @param {string} namespace where this belongs\n * @param {string} resolverName resolver\n * @param {array} args arguments\n * @return {void} nothing\n */\nfunction actionCall(ee, namespace, resolverName, args = []) {\n debugFn(`actionCall: ${namespace} ${resolverName}`, args)\n ee.$trigger(createEvt(namespace, EMIT_EVT), [\n resolverName,\n toArray(args)\n ])\n}\n\n/**\n * break out to use in different places to handle the return from server\n * @param {object} data from server\n * @param {function} resolver from promise\n * @param {function} rejecter from promise\n * @return {void} nothing\n */\nfunction respondHandler(data, resolver, rejecter) {\n if (isKeyInObject(data, 'error')) {\n debugFn('rejecter called', data.error)\n rejecter(data.error)\n } else if (isKeyInObject(data, 'data')) {\n debugFn('resolver called', data.data)\n resolver(data.data)\n } else {\n debugFn('UNKNOWN_RESULT', data)\n rejecter({message: UNKNOWN_RESULT, error: data})\n }\n}\n\n/**\n * Add extra property to the resolver\n * @param {string} namespace where this belongs\n * @param {string} resolverName name as event name\n * @param {object} params from contract\n * @param {function} fn resolver function\n * @param {object} ee EventEmitter\n * @return {function} resolver\n */\nconst setupResolver = (namespace, resolverName, params, fn, ee) => {\n // also need to setup a getter to get back the namespace of this resolver\n if (Object.getOwnPropertyDescriptor(fn, MY_NAMESPACE) === undefined) {\n Object.defineProperty(fn, MY_NAMESPACE, {\n value: namespace,\n writeable: false\n })\n }\n // onResult handler\n if (Object.getOwnPropertyDescriptor(fn, RESULT_PROP_NAME) === undefined) {\n Object.defineProperty(fn, RESULT_PROP_NAME, {\n set: function(resultCallback) {\n if (typeof resultCallback === 'function') {\n ee.$only(\n createEvt(namespace, resolverName, RESULT_PROP_NAME),\n function resultHandler(result) {\n respondHandler(result, resultCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error)\n })\n }\n )\n }\n },\n get: function() {\n return null;\n }\n })\n }\n // we do need to add the send prop back because it's the only way to deal with\n // bi-directional data stream\n if (Object.getOwnPropertyDescriptor(fn, MESSAGE_PROP_NAME) === undefined) {\n Object.defineProperty(fn, MESSAGE_PROP_NAME, {\n set: function(messageCallback) {\n // we expect this to be a function\n if (typeof messageCallback === 'function') {\n // did that add to the callback\n let onMessageCallback = (args) => {\n respondHandler(args, messageCallback, (error) => {\n ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error)\n })\n }\n // register the handler for this message event\n ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback)\n }\n },\n get: function() {\n return null; // just return nothing\n }\n })\n }\n // add an ERROR_PROP_NAME handler\n if (Object.getOwnPropertyDescriptor(fn, ERROR_PROP_NAME) === undefined) {\n Object.defineProperty(fn, ERROR_PROP_NAME, {\n set: function(resolverErrorHandler) {\n if (typeof resolverErrorHandler === 'function') {\n // please note ERROR_PROP_NAME can add multiple listners\n ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler)\n }\n },\n get: function() {\n return null;\n }\n })\n }\n // pairing with the server vesrion SEND_MSG_PROP_NAME\n if (Object.getOwnPropertyDescriptor(fn, SEND_MSG_PROP_NAME) === undefined) {\n Object.defineProperty(fn, SEND_MSG_PROP_NAME, {\n set: function(messagePayload) {\n const result = validateSync(toArray(messagePayload), params.params, true)\n // here is the different we don't throw erro instead we trigger an\n // onError\n if (result[ERROR_KEY] && result[ERROR_KEY].length) {\n ee.$call(\n createEvt(namespace, resolverName, ERROR_PROP_NAME),\n [JsonqlValidationError(resolverName, result[ERROR_KEY])]\n )\n } else {\n // there is no return only an action call\n actionCall(ee, namespace, resolverName, result[DATA_KEY])\n }\n },\n get: function() {\n return null; // just return nothing\n }\n })\n }\n return fn;\n}\n\n/**\n * The problem is the namespace can have more than one\n * and we only have on onError message\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {void}\n */\nconst createNamespaceErrorHandler = (obj, ee, nspSet) => {\n // using the onError as name\n // @TODO we should follow the convention earlier\n // make this a setter for the obj itself\n if (Object.getOwnPropertyDescriptor(obj, ERROR_PROP_NAME) === undefined) {\n Object.defineProperty(obj, ERROR_PROP_NAME, {\n set: function(namespaceErrorHandler) {\n if (typeof namespaceErrorHandler === 'function') {\n // please note ERROR_PROP_NAME can add multiple listners\n for (let namespace in nspSet) {\n // this one is very tricky, we need to make sure the trigger is calling\n // with the namespace as well as the error\n ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler)\n }\n }\n },\n get: function() {\n return null;\n }\n })\n }\n}\n\n/**\n * This event will fire when the socket.io.on('connection') and ws.onopen\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} nspSet namespace keys\n * @return {void}\n */\nconst createOnReadyhandler = (obj, ee, nspSet) => {\n if (Object.getOwnPropertyDescriptor(obj, READY_PROP_NAME) === undefined) {\n Object.defineProperty(obj, READY_PROP_NAME, {\n set: function(onReadyCallback) {\n if (typeof onReadyCallback === 'function') {\n // reduce it down to just one flat level\n let result = ee.$on(READY_PROP_NAME, onReadyCallback)\n }\n },\n get: function() {\n return null;\n }\n })\n }\n}\n\n/**\n * Create auth related methods\n * @param {object} obj the client itself\n * @param {object} ee Event Emitter\n * @param {object} opts configuration\n * @return {void}\n */\nconst createAuthMethods = (obj, ee, opts) => {\n if (opts.enableAuth) {\n // create an additonal login handler\n // we require the token\n obj[opts.loginHandlerName] = (token) => {\n debugFn(opts.loginHandlerName, token)\n if (token && isString(token)) {\n return ee.$trigger(LOGIN_EVENT_NAME, [token])\n }\n throw new JsonqlValidationError(opts.loginHandlerName)\n }\n // logout event handler\n obj[opts.logoutHandlerName] = (...args) => {\n ee.$trigger(LOGOUT_EVENT_NAME, args)\n }\n }\n}\n","// main api to get the ws-client\n\nimport createSocketClient from './create-socket-client'\nimport generator from './generator'\n\nimport { checkOptions, ee, processContract } from './utils'\n\n/**\n * The main interface to create the wsClient for use\n * @param {function} clientGenerator this is an internal way to generate node or browser client\n * @return {function} wsClient\n * @public\n */\nexport default function main(clientGenerator) {\n /**\n * @param {object} config configuration\n * @param {object} [eventEmitter=false] this will be the bridge between clients\n * @return {object} wsClient\n */\n const wsClient = (config, eventEmitter = false) => {\n return checkOptions(config)\n .then(opts => ({\n opts,\n nspMap: processContract(opts),\n ee: eventEmitter || new ee()\n })\n )\n .then(clientGenerator)\n .then(\n ({ opts, nspMap, ee }) => createSocketClient(opts, nspMap, ee)\n )\n .then(\n ({ opts, nspMap, ee }) => generator(opts, nspMap, ee)\n )\n .catch(err => {\n console.error('jsonql-ws-client init error', err)\n })\n }\n // use the Object.addProperty trick\n Object.defineProperty(wsClient, 'CLIENT_TYPE_INFO', {\n value: '__PLACEHOLDER__',\n writable: false\n })\n return wsClient;\n}\n","// This is the module entry point\nimport clientGenerator from './src/utils/client-generator'\nimport main from './src/main'\n\nexport default main(clientGenerator)\n"],"names":[],"mappings":";;;;;;;;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ECAA;;;;;;;;;;"} \ No newline at end of file diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index 56d143a9..c0e9c929 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -37,6 +37,7 @@ "jsonql-params-validator": "^1.4.11", "jsonql-resolver": "^0.9.4", "jsonql-utils": "^0.7.4", + "jsonql-ws-client": "^1.0.0-beta.1", "lodash": "^4.17.15", "ws": "^7.1.2" }, -- Gitee From e47c0bac93fd14596073db66a370d22291c2e11d Mon Sep 17 00:00:00 2001 From: joelchu Date: Sun, 13 Oct 2019 19:27:32 +0800 Subject: [PATCH 05/24] remove the jsonql-ws-client --- packages/ws-server/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index c0e9c929..56d143a9 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -37,7 +37,6 @@ "jsonql-params-validator": "^1.4.11", "jsonql-resolver": "^0.9.4", "jsonql-utils": "^0.7.4", - "jsonql-ws-client": "^1.0.0-beta.1", "lodash": "^4.17.15", "ws": "^7.1.2" }, -- Gitee From 43eed816fd51a48c219ddd6087c57dca940c236d Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 14 Oct 2019 16:16:03 +0800 Subject: [PATCH 06/24] finalize on the api structure and change the name to api.js --- packages/ws-client/src/{main.js => api.js} | 7 ++-- packages/ws-client/src/index.js | 45 ---------------------- 2 files changed, 3 insertions(+), 49 deletions(-) rename packages/ws-client/src/{main.js => api.js} (75%) delete mode 100644 packages/ws-client/src/index.js diff --git a/packages/ws-client/src/main.js b/packages/ws-client/src/api.js similarity index 75% rename from packages/ws-client/src/main.js rename to packages/ws-client/src/api.js index d210edec..2744c0a9 100644 --- a/packages/ws-client/src/main.js +++ b/packages/ws-client/src/api.js @@ -7,11 +7,10 @@ import checkOptions from './options' import { ee, processContract } from './utils' /** - * @param {object} opts configuration @NOTE we expect the contract and eventEmitter to be part of the opts - * @param {object} socketClient we normalize the auth and non auth client from now on + * @param {object} socketClientResolver we normalize the auth and non auth client from now on * @return {object} the wsClient instance with all the available API */ -export default function wsClient(opts, socketClient) { +export default function wsClient(socketClientResolver) { const { eventEmitter } = opts; // we need to inject property to this client later // therefore we need to do it this way @@ -23,7 +22,7 @@ export default function wsClient(opts, socketClient) { ee: eventEmitter || new ee() })) .then( - ({opts, nspMap, ee}) => createSocketClient(opts, nspMap, ee, socketClient) + ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee) ) // @TODO the generator should be part of the http client .then( diff --git a/packages/ws-client/src/index.js b/packages/ws-client/src/index.js deleted file mode 100644 index a520ff3d..00000000 --- a/packages/ws-client/src/index.js +++ /dev/null @@ -1,45 +0,0 @@ -// This was in the main.js - just put it here for now - -import createSocketClient from './create-socket-client' -import generator from './generator' - -import { checkOptions, ee, processContract } from './utils' - -/** - * The main interface to create the wsClient for use - * @param {function} clientGenerator this is an internal way to generate node or browser client - * @return {function} wsClient - * @public - */ -export default function main(clientGenerator) { - /** - * @param {object} config configuration - * @param {object} [eventEmitter=false] this will be the bridge between clients - * @return {object} wsClient - */ - const wsClient = (config, eventEmitter = false) => { - return checkOptions(config) - .then(opts => ({ - opts, - nspMap: processContract(opts), - ee: eventEmitter || new ee() - }) - ) - .then(clientGenerator) - .then( - ({ opts, nspMap, ee }) => createSocketClient(opts, nspMap, ee) - ) - .then( - ({ opts, nspMap, ee }) => generator(opts, nspMap, ee) - ) - .catch(err => { - console.error('jsonql-ws-client init error', err) - }) - } - // use the Object.addProperty trick - Object.defineProperty(wsClient, 'CLIENT_TYPE_INFO', { - value: '__PLACEHOLDER__', - writable: false - }) - return wsClient; -} -- Gitee From 7f35e738d5d62cb6752af33aefd0f18d652b253a Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 14 Oct 2019 16:16:58 +0800 Subject: [PATCH 07/24] move the old code into the test/fixtures folder because we will need it to develop and test the ws client --- packages/ws-client/{ => tests/fixtures}/beta/index.js | 0 packages/ws-client/{ => tests/fixtures}/beta/main.js | 0 .../{ => tests/fixtures}/beta/src/client-event-handler.js | 0 .../{ => tests/fixtures}/beta/src/create-socket-client.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/generator.js | 0 .../ws-client/{ => tests/fixtures}/beta/src/io/create-client.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/io/index.js | 0 .../ws-client/{ => tests/fixtures}/beta/src/io/io-main-handler.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/main.js | 0 .../{ => tests/fixtures}/beta/src/node/client-generator.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/node/main.cjs.js | 0 .../{ => tests/fixtures}/beta/src/utils/check-options.js | 0 .../{ => tests/fixtures}/beta/src/utils/client-generator.js | 0 .../ws-client/{ => tests/fixtures}/beta/src/utils/constants.js | 0 .../{ => tests/fixtures}/beta/src/utils/create-nsp-client.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/utils/ee.js | 0 .../ws-client/{ => tests/fixtures}/beta/src/utils/get-debug.js | 0 .../{ => tests/fixtures}/beta/src/utils/get-namespace-in-order.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/utils/index.js | 0 .../{ => tests/fixtures}/beta/src/utils/process-contract.js | 0 .../fixtures}/beta/src/utils/trigger-namespaces-on-error.js | 0 .../ws-client/{ => tests/fixtures}/beta/src/ws/create-client.js | 0 .../{ => tests/fixtures}/beta/src/ws/extract-ws-payload.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/ws/index.js | 0 .../ws-client/{ => tests/fixtures}/beta/src/ws/ws-main-handler.js | 0 packages/ws-client/{ => tests/fixtures}/beta/src/ws/ws.js | 0 26 files changed, 0 insertions(+), 0 deletions(-) rename packages/ws-client/{ => tests/fixtures}/beta/index.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/main.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/client-event-handler.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/create-socket-client.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/generator.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/io/create-client.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/io/index.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/io/io-main-handler.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/main.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/node/client-generator.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/node/main.cjs.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/check-options.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/client-generator.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/constants.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/create-nsp-client.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/ee.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/get-debug.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/get-namespace-in-order.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/index.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/process-contract.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/utils/trigger-namespaces-on-error.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/ws/create-client.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/ws/extract-ws-payload.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/ws/index.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/ws/ws-main-handler.js (100%) rename packages/ws-client/{ => tests/fixtures}/beta/src/ws/ws.js (100%) diff --git a/packages/ws-client/beta/index.js b/packages/ws-client/tests/fixtures/beta/index.js similarity index 100% rename from packages/ws-client/beta/index.js rename to packages/ws-client/tests/fixtures/beta/index.js diff --git a/packages/ws-client/beta/main.js b/packages/ws-client/tests/fixtures/beta/main.js similarity index 100% rename from packages/ws-client/beta/main.js rename to packages/ws-client/tests/fixtures/beta/main.js diff --git a/packages/ws-client/beta/src/client-event-handler.js b/packages/ws-client/tests/fixtures/beta/src/client-event-handler.js similarity index 100% rename from packages/ws-client/beta/src/client-event-handler.js rename to packages/ws-client/tests/fixtures/beta/src/client-event-handler.js diff --git a/packages/ws-client/beta/src/create-socket-client.js b/packages/ws-client/tests/fixtures/beta/src/create-socket-client.js similarity index 100% rename from packages/ws-client/beta/src/create-socket-client.js rename to packages/ws-client/tests/fixtures/beta/src/create-socket-client.js diff --git a/packages/ws-client/beta/src/generator.js b/packages/ws-client/tests/fixtures/beta/src/generator.js similarity index 100% rename from packages/ws-client/beta/src/generator.js rename to packages/ws-client/tests/fixtures/beta/src/generator.js diff --git a/packages/ws-client/beta/src/io/create-client.js b/packages/ws-client/tests/fixtures/beta/src/io/create-client.js similarity index 100% rename from packages/ws-client/beta/src/io/create-client.js rename to packages/ws-client/tests/fixtures/beta/src/io/create-client.js diff --git a/packages/ws-client/beta/src/io/index.js b/packages/ws-client/tests/fixtures/beta/src/io/index.js similarity index 100% rename from packages/ws-client/beta/src/io/index.js rename to packages/ws-client/tests/fixtures/beta/src/io/index.js diff --git a/packages/ws-client/beta/src/io/io-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/io/io-main-handler.js similarity index 100% rename from packages/ws-client/beta/src/io/io-main-handler.js rename to packages/ws-client/tests/fixtures/beta/src/io/io-main-handler.js diff --git a/packages/ws-client/beta/src/main.js b/packages/ws-client/tests/fixtures/beta/src/main.js similarity index 100% rename from packages/ws-client/beta/src/main.js rename to packages/ws-client/tests/fixtures/beta/src/main.js diff --git a/packages/ws-client/beta/src/node/client-generator.js b/packages/ws-client/tests/fixtures/beta/src/node/client-generator.js similarity index 100% rename from packages/ws-client/beta/src/node/client-generator.js rename to packages/ws-client/tests/fixtures/beta/src/node/client-generator.js diff --git a/packages/ws-client/beta/src/node/main.cjs.js b/packages/ws-client/tests/fixtures/beta/src/node/main.cjs.js similarity index 100% rename from packages/ws-client/beta/src/node/main.cjs.js rename to packages/ws-client/tests/fixtures/beta/src/node/main.cjs.js diff --git a/packages/ws-client/beta/src/utils/check-options.js b/packages/ws-client/tests/fixtures/beta/src/utils/check-options.js similarity index 100% rename from packages/ws-client/beta/src/utils/check-options.js rename to packages/ws-client/tests/fixtures/beta/src/utils/check-options.js diff --git a/packages/ws-client/beta/src/utils/client-generator.js b/packages/ws-client/tests/fixtures/beta/src/utils/client-generator.js similarity index 100% rename from packages/ws-client/beta/src/utils/client-generator.js rename to packages/ws-client/tests/fixtures/beta/src/utils/client-generator.js diff --git a/packages/ws-client/beta/src/utils/constants.js b/packages/ws-client/tests/fixtures/beta/src/utils/constants.js similarity index 100% rename from packages/ws-client/beta/src/utils/constants.js rename to packages/ws-client/tests/fixtures/beta/src/utils/constants.js diff --git a/packages/ws-client/beta/src/utils/create-nsp-client.js b/packages/ws-client/tests/fixtures/beta/src/utils/create-nsp-client.js similarity index 100% rename from packages/ws-client/beta/src/utils/create-nsp-client.js rename to packages/ws-client/tests/fixtures/beta/src/utils/create-nsp-client.js diff --git a/packages/ws-client/beta/src/utils/ee.js b/packages/ws-client/tests/fixtures/beta/src/utils/ee.js similarity index 100% rename from packages/ws-client/beta/src/utils/ee.js rename to packages/ws-client/tests/fixtures/beta/src/utils/ee.js diff --git a/packages/ws-client/beta/src/utils/get-debug.js b/packages/ws-client/tests/fixtures/beta/src/utils/get-debug.js similarity index 100% rename from packages/ws-client/beta/src/utils/get-debug.js rename to packages/ws-client/tests/fixtures/beta/src/utils/get-debug.js diff --git a/packages/ws-client/beta/src/utils/get-namespace-in-order.js b/packages/ws-client/tests/fixtures/beta/src/utils/get-namespace-in-order.js similarity index 100% rename from packages/ws-client/beta/src/utils/get-namespace-in-order.js rename to packages/ws-client/tests/fixtures/beta/src/utils/get-namespace-in-order.js diff --git a/packages/ws-client/beta/src/utils/index.js b/packages/ws-client/tests/fixtures/beta/src/utils/index.js similarity index 100% rename from packages/ws-client/beta/src/utils/index.js rename to packages/ws-client/tests/fixtures/beta/src/utils/index.js diff --git a/packages/ws-client/beta/src/utils/process-contract.js b/packages/ws-client/tests/fixtures/beta/src/utils/process-contract.js similarity index 100% rename from packages/ws-client/beta/src/utils/process-contract.js rename to packages/ws-client/tests/fixtures/beta/src/utils/process-contract.js diff --git a/packages/ws-client/beta/src/utils/trigger-namespaces-on-error.js b/packages/ws-client/tests/fixtures/beta/src/utils/trigger-namespaces-on-error.js similarity index 100% rename from packages/ws-client/beta/src/utils/trigger-namespaces-on-error.js rename to packages/ws-client/tests/fixtures/beta/src/utils/trigger-namespaces-on-error.js diff --git a/packages/ws-client/beta/src/ws/create-client.js b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js similarity index 100% rename from packages/ws-client/beta/src/ws/create-client.js rename to packages/ws-client/tests/fixtures/beta/src/ws/create-client.js diff --git a/packages/ws-client/beta/src/ws/extract-ws-payload.js b/packages/ws-client/tests/fixtures/beta/src/ws/extract-ws-payload.js similarity index 100% rename from packages/ws-client/beta/src/ws/extract-ws-payload.js rename to packages/ws-client/tests/fixtures/beta/src/ws/extract-ws-payload.js diff --git a/packages/ws-client/beta/src/ws/index.js b/packages/ws-client/tests/fixtures/beta/src/ws/index.js similarity index 100% rename from packages/ws-client/beta/src/ws/index.js rename to packages/ws-client/tests/fixtures/beta/src/ws/index.js diff --git a/packages/ws-client/beta/src/ws/ws-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js similarity index 100% rename from packages/ws-client/beta/src/ws/ws-main-handler.js rename to packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js diff --git a/packages/ws-client/beta/src/ws/ws.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws.js similarity index 100% rename from packages/ws-client/beta/src/ws/ws.js rename to packages/ws-client/tests/fixtures/beta/src/ws/ws.js -- Gitee From fd405b3eef57ea0406f37a5f0b2da30637249c82 Mon Sep 17 00:00:00 2001 From: joelchu Date: Mon, 14 Oct 2019 16:27:15 +0800 Subject: [PATCH 08/24] setting up the final interface for testing development --- packages/ws-client/tests/fixtures/beta/main.js | 6 ------ .../tests/fixtures/beta/ws-client-resolver.js | 13 +++++++++++++ .../ws-client/tests/fixtures/jsonql-ws-client.js | 6 ++++++ 3 files changed, 19 insertions(+), 6 deletions(-) delete mode 100644 packages/ws-client/tests/fixtures/beta/main.js create mode 100644 packages/ws-client/tests/fixtures/beta/ws-client-resolver.js create mode 100644 packages/ws-client/tests/fixtures/jsonql-ws-client.js diff --git a/packages/ws-client/tests/fixtures/beta/main.js b/packages/ws-client/tests/fixtures/beta/main.js deleted file mode 100644 index d8bb48a4..00000000 --- a/packages/ws-client/tests/fixtures/beta/main.js +++ /dev/null @@ -1,6 +0,0 @@ -// the node client main interface -const main = require('./src/node/main.cjs') -const clientGenerator = require('./src/node/client-generator') - -// finally export it -module.exports = main(clientGenerator) diff --git a/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js b/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js new file mode 100644 index 00000000..ee41a889 --- /dev/null +++ b/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js @@ -0,0 +1,13 @@ +// this will be the news style interface that will pass to the jsonql-ws-client +// then return a function for accepting an opts to generate the final +// client api + +/** + * @param {object} opts configuration + * @param {object} nspMap from the contract + * @param {object} ee instance of the eventEmitter + * @return {object} passing the same 3 input out with additional in the opts + */ +export default function wsClientResolver(opts, nspMap, ee) { + +} diff --git a/packages/ws-client/tests/fixtures/jsonql-ws-client.js b/packages/ws-client/tests/fixtures/jsonql-ws-client.js new file mode 100644 index 00000000..6e88b950 --- /dev/null +++ b/packages/ws-client/tests/fixtures/jsonql-ws-client.js @@ -0,0 +1,6 @@ +// this will create the final client + +import wsClientResolver from './beta/ws-client-resolver' +import jsonqlWsClient from '../src/api' +// export back the function and that's it +export default jsonqlWsClient(wsClientResolver) -- Gitee From 274be70e424836b278e825d481dd147ce9f24949 Mon Sep 17 00:00:00 2001 From: joelchu Date: Tue, 15 Oct 2019 11:00:34 +0800 Subject: [PATCH 09/24] mapping the top level createClient to the beta test code --- .../tests/fixtures/beta/ws-client-resolver.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js b/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js index ee41a889..860db499 100644 --- a/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js +++ b/packages/ws-client/tests/fixtures/beta/ws-client-resolver.js @@ -1,6 +1,19 @@ // this will be the news style interface that will pass to the jsonql-ws-client // then return a function for accepting an opts to generate the final // client api +import WebSocket from 'ws' +import { TOKEN_PARAM_NAME } from 'jsonql-constants' +import createClient from './src/ws' +/** + * Create a client with auth token + * @param {string} url start with ws:// @TODO check this? + * @param {string} [token = false] the jwt token + * @return {object} ws instance + */ +function client(url, token = false) { + let uri = token ? `${url}?${TOKEN_PARAM_NAME}=${token}` : url; + return new WebSocket(uri) +} /** * @param {object} opts configuration @@ -9,5 +22,7 @@ * @return {object} passing the same 3 input out with additional in the opts */ export default function wsClientResolver(opts, nspMap, ee) { - + opts.nspClient = client; + opts.nspAuthClient = client; + return createClient(opts, nspMap, ee) } -- Gitee From 87fd451f0c08c7ac391a94a62573a357ae8300df Mon Sep 17 00:00:00 2001 From: joelchu Date: Tue, 15 Oct 2019 11:02:03 +0800 Subject: [PATCH 10/24] add ws to deps --- packages/ws-client/package.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index 1ad20a01..b5611dac 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -51,16 +51,17 @@ "node": ">=8" }, "dependencies": { - "esm": "^3.2.25", "jsonql-constants": "^1.8.4", "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.2", "jsonql-params-validator": "^1.4.11", "jsonql-utils": "^0.7.5", - "nb-event-service": "^1.8.3" + "nb-event-service": "^1.8.3", + "ws": "^7.1.2" }, "devDependencies": { "ava": "^2.4.0", + "esm": "^3.2.25", "fs-extra": "^8.1.0", "kefir": "^3.8.6" }, -- Gitee From f82cdca57d12f5cdd597d66485d71264783b445b Mon Sep 17 00:00:00 2001 From: joelchu Date: Tue, 15 Oct 2019 11:42:08 +0800 Subject: [PATCH 11/24] remapping all the modules path --- packages/ws-client/package.json | 14 ++--- packages/ws-client/src/api.js | 2 +- .../ws-client/src/core/client-generator.js | 2 +- .../ws-client/src/core/create-nsp-client.js | 2 +- .../src/core/create-socket-client.js | 29 ---------- .../ws-client/src/core/map-event-to-client.js | 5 +- packages/ws-client/src/options/index.js | 2 +- packages/ws-client/src/utils/index.js | 23 +++++--- .../tests/fixtures/jsonql-ws-client.js | 2 +- packages/ws-client/tests/test-node.test.js | 56 +++++++------------ 10 files changed, 49 insertions(+), 88 deletions(-) delete mode 100644 packages/ws-client/src/core/create-socket-client.js diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index b5611dac..3a003716 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -13,11 +13,7 @@ ], "scripts": { "test": "ava --verbose", - "prepare": "npm run build && npm run test", - "build": "npm run build:browser && npm run build:cjs", - "build:browser": "NODE_ENV=umd rollup -c", - "build:cjs": "NODE_ENV=cjs rollup -c ./rollup.config.node.js", - "build:test": "NODE_ENV=test rollup -c ./rollup.config.node.js", + "test:node": "DEBUG=jsonql-ws-client* ava --verbose ./tests/test-node.test.js", "contract": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config.js", "contract:auth": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config-auth.js" }, @@ -56,14 +52,16 @@ "jsonql-jwt": "^1.3.2", "jsonql-params-validator": "^1.4.11", "jsonql-utils": "^0.7.5", - "nb-event-service": "^1.8.3", - "ws": "^7.1.2" + "nb-event-service": "^1.8.3" }, "devDependencies": { "ava": "^2.4.0", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "kefir": "^3.8.6" + "jsonql-contract": "^1.7.21", + "jsonql-ws-server": "^1.3.0", + "kefir": "^3.8.6", + "ws": "^7.1.2" }, "repository": { "type": "git", diff --git a/packages/ws-client/src/api.js b/packages/ws-client/src/api.js index 2744c0a9..eb64719d 100644 --- a/packages/ws-client/src/api.js +++ b/packages/ws-client/src/api.js @@ -18,7 +18,7 @@ export default function wsClient(socketClientResolver) { checkOptions(opts) .then(opts => ({ opts, - nspMap: processContract(opts) + nspMap: processContract(opts), ee: eventEmitter || new ee() })) .then( diff --git a/packages/ws-client/src/core/client-generator.js b/packages/ws-client/src/core/client-generator.js index a7f7a6c9..b65712d3 100644 --- a/packages/ws-client/src/core/client-generator.js +++ b/packages/ws-client/src/core/client-generator.js @@ -11,7 +11,7 @@ import { isString } from 'jsonql-params-validator' import { JsonqlError } from 'jsonql-errors' import { SOCKET_IO, WS } from './constants' // import { IO_ROUNDTRIP_LOGIN, IO_HANDSHAKE_LOGIN } from 'jsonql-constants' -import getDebug from './get-debug' +import { getDebug } from '../utils' const debug = getDebug('client-generator') /** diff --git a/packages/ws-client/src/core/create-nsp-client.js b/packages/ws-client/src/core/create-nsp-client.js index 9b656813..bd4e7402 100644 --- a/packages/ws-client/src/core/create-nsp-client.js +++ b/packages/ws-client/src/core/create-nsp-client.js @@ -2,7 +2,7 @@ // pre-defined in the client-generator // and this one will have the same parameters // and the callback is identical -import getDebug from './get-debug' +import { getDebug } from '../utils' const debugFn = getDebug('create-nsp-client') /** * wrapper method to create a nsp without login diff --git a/packages/ws-client/src/core/create-socket-client.js b/packages/ws-client/src/core/create-socket-client.js deleted file mode 100644 index 60b4df6c..00000000 --- a/packages/ws-client/src/core/create-socket-client.js +++ /dev/null @@ -1,29 +0,0 @@ -// import { JsonqlError } from 'jsonql-errors' -/* -this have moved out of this package -@TODO need to figure out how to inject them back here -import createWsClient from './ws' -import createIoClient from './io' -*/ -// import { SOCKET_IO, WS, SOCKET_NOT_DEFINE_ERR } from './utils/constants' - -/** - * get the create client instance function - * @param {string} type of client - * @return {function} the actual methods - * @public - */ -export default function createSocketClient(opts, nspMap, ee) { - // idea, instead of serverType we pass the create client method via the opts - return Reflect.apply(opts.createClientMethod, null, [opts, nspMap, ee]) - /* - switch (opts.serverType) { - case SOCKET_IO: - return createIoClient(opts, nspMap, ee) - case WS: - return createWsClient(opts, nspMap, ee) - default: - throw new JsonqlError(SOCKET_NOT_DEFINE_ERR) - } - */ -} diff --git a/packages/ws-client/src/core/map-event-to-client.js b/packages/ws-client/src/core/map-event-to-client.js index f64c3a41..a0c11505 100644 --- a/packages/ws-client/src/core/map-event-to-client.js +++ b/packages/ws-client/src/core/map-event-to-client.js @@ -4,12 +4,12 @@ import { chainPromises } from 'jsonql-jwt' import { getNameFromPayload, isString } from 'jsonql-params-validator' import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants' +import { getNamespaceInOrder } from 'jsonql-utils' -import { nspClient, nspAuthClient } from '../utils/create-nsp-client' import clientEventHandler from '../client-event-handler' import ioMainHandler from './io-main-handler' -import { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils' +import { getDebug, clearMainEmitEvt, disconnect } from '../utils' const debugFn = getDebug('io-create-client') // just to make it less ugly @@ -28,6 +28,7 @@ const mapNsps = (nsps, namespaces) => nsps const createAuthNsps = function(opts, nspMap, token, namespaces) { let { publicNamespace } = nspMap; opts.token = token; + let { nspAuthClient, nspClient } = opts; // @TODO seems that we still need to create two seperate type of clients let p1 = () => nspAuthClient(namespaces[0], opts) let p2 = () => nspClient(namespaces[1], opts) diff --git a/packages/ws-client/src/options/index.js b/packages/ws-client/src/options/index.js index 58eb1225..94d271c7 100644 --- a/packages/ws-client/src/options/index.js +++ b/packages/ws-client/src/options/index.js @@ -21,7 +21,7 @@ import { } from 'jsonql-constants' // this should be remove - we have to make it generic import { SOCKET_IO, WS, AVAILABLE_SERVERS } from './constants' -import { getDebug } from '../utils' +import { fixWss, getHostName, getDebug } from '../utils' const debug = getDebug('check-options') // constant props const constProps = { diff --git a/packages/ws-client/src/utils/index.js b/packages/ws-client/src/utils/index.js index 31dc4508..0507fa6f 100644 --- a/packages/ws-client/src/utils/index.js +++ b/packages/ws-client/src/utils/index.js @@ -1,22 +1,29 @@ // export the util methods +import { isArray } from 'jsonql-params-validator' +// moved to jsonql-utils +import { toArray, createEvt } from 'jsonql-utils' import ee from './ee' import getDebug from './get-debug' - import processContract from './process-contract' -import { isArray } from 'jsonql-params-validator' -// moved to jsonql-utils -import { toArray, createEvt } from 'jsonql-utils' +import { + fixWss, + getHostName, + clearMainEmitEvt, + disconnect +} from './helpers' // export export { + isArray, + toArray, createEvt, - clearMainEmitEvt, - checkOptions, ee, getDebug, processContract, - toArray, - formatPayload, + + fixWss, + getHostName, + clearMainEmitEvt, disconnect } diff --git a/packages/ws-client/tests/fixtures/jsonql-ws-client.js b/packages/ws-client/tests/fixtures/jsonql-ws-client.js index 6e88b950..6b030325 100644 --- a/packages/ws-client/tests/fixtures/jsonql-ws-client.js +++ b/packages/ws-client/tests/fixtures/jsonql-ws-client.js @@ -1,6 +1,6 @@ // this will create the final client import wsClientResolver from './beta/ws-client-resolver' -import jsonqlWsClient from '../src/api' +import jsonqlWsClient from '../../src/api' // export back the function and that's it export default jsonqlWsClient(wsClientResolver) diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index af83dde7..a9d1f095 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -8,72 +8,56 @@ const fsx = require('fs-extra') const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') +const jsonqlWsClient = require('./fixtures/jsonql-ws-client') + const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json')) -const { NOT_LOGIN_ERR_MSG, JS_WS_SOCKET_IO_NAME, JS_WS_NAME } = require('jsonql-constants') +const { NOT_LOGIN_ERR_MSG, JS_WS_NAME } = require('jsonql-constants') const payload = {name: 'Joel'}; const token = genToken(payload) const port = 8010; const url = `ws://localhost:${port}` -//////////////////// + +/* const { chainCreateNsps, clientGenerator, es } = require('./fixtures/node') - +*/ /// PREPARE TEST /// test.before(async t => { const { io, app } = await serverSetup({ contract, contractDir, resolverDir: join(__dirname, 'fixtures', 'resolvers'), - serverType: JS_WS_SOCKET_IO_NAME, + serverType: JS_WS_NAME, enableAuth: true, - useJwt: true, keysDir: join(__dirname, 'fixtures', 'keys') }) t.context.server = app.listen(port) - let config = { opts: { serverType: JS_WS_SOCKET_IO_NAME }, nspMap: {}, ee: es }; - let { opts, ee } = clientGenerator(config) - t.context.opts = opts; - t.context.ee = ee; + t.context.client = jsonqlWsClient({ + hostname: url, + serverType: JS_WS_NAME + }) + }) // real test start here -test.serial.cb('It should able to replace the same event with new method', t => { +test.serial.only('It should able to replace the same event with new method', t => { + + const client = t.context.client; + + debug(client) + + t.pass() - t.plan(3) - // try a sequence with swapping out the event handler - let ee = t.context.ee; - let evtName = 'main-event'; - let fnName = 'testFn'; - - ee.$on(evtName, (from, value) => { - debug(evtName, from, value) - // (1) - t.is(from, fnName) - return ++value; - }) - // first trigger it - ee.$call(evtName, [fnName, 1]) - // (2) - t.is(ee.$done, 2) - // now replace this event with another callback - ee.$replace(evtName, (from, value) => { - debug(evtName, from, value) - // (3) - t.is(value, 3) - t.end() - return --value; - }) - ee.$call(evtName, [fnName, 3]) }) -test.serial.cb.only('It should able to resolve the promise one after the other', t => { +test.serial.cb('It should able to resolve the promise one after the other', t => { t.plan(1) let opts = t.context.opts; let p1 = () => opts.nspAuthClient([url, 'jsonql/private'].join('/'), token) -- Gitee From 5e3b080c3eafac60338a947b6a5d612361a5dd8b Mon Sep 17 00:00:00 2001 From: joelchu Date: Tue, 15 Oct 2019 14:49:00 +0800 Subject: [PATCH 12/24] fixing some of the moodule mapping --- packages/ws-client/src/api.js | 3 +- .../ws-client/src/core/client-generator.js | 46 ------------------- packages/ws-client/src/options/index.js | 13 ++---- 3 files changed, 4 insertions(+), 58 deletions(-) delete mode 100644 packages/ws-client/src/core/client-generator.js diff --git a/packages/ws-client/src/api.js b/packages/ws-client/src/api.js index eb64719d..9d44e92d 100644 --- a/packages/ws-client/src/api.js +++ b/packages/ws-client/src/api.js @@ -1,11 +1,10 @@ // the top level API // The goal is to create a generic method that will able to handle // any kind of clients -import createSocketClient from './core/create-socket-client' import generator from './core/generator' import checkOptions from './options' - import { ee, processContract } from './utils' + /** * @param {object} socketClientResolver we normalize the auth and non auth client from now on * @return {object} the wsClient instance with all the available API diff --git a/packages/ws-client/src/core/client-generator.js b/packages/ws-client/src/core/client-generator.js deleted file mode 100644 index b65712d3..00000000 --- a/packages/ws-client/src/core/client-generator.js +++ /dev/null @@ -1,46 +0,0 @@ -// generate the web socket connect client for browser -import { - socketIoRoundtripLogin, - socketIoClientAsync, - socketIoHandshakeLogin, - wsAuthClient, - wsClient -} from 'jsonql-jwt' - -import { isString } from 'jsonql-params-validator' -import { JsonqlError } from 'jsonql-errors' -import { SOCKET_IO, WS } from './constants' -// import { IO_ROUNDTRIP_LOGIN, IO_HANDSHAKE_LOGIN } from 'jsonql-constants' -import { getDebug } from '../utils' -const debug = getDebug('client-generator') - -/** - * create the web socket client - * @param {object} payload passing - * @return {object} just mutate it then pass it on - */ -export default function clientGenerator({opts, nspMap, ee}) { - switch (opts.serverType) { - case SOCKET_IO: - opts.nspClient = (...args) => ( - Reflect.apply(socketIoClientAsync, null, [io, ...args]) - ) - if (isString(opts.useJwt)) { - opts.nspAuthClient = (...args) => ( - Reflect.apply(socketIoRoundtripLogin, null, [io, ...args]) - ) - } else { - opts.nspAuthClient = (...args) => ( - Reflect.apply(socketIoHandshakeLogin, null, [io, ...args]) - ) - } - break; - case WS: - opts.nspClient = wsClient; - opts.nspAuthClient = wsAuthClient; - break; - default: - throw new JsonqlError(`Unknown serverType: ${opts.serverType}`) - } - return {opts, nspMap, ee} -} diff --git a/packages/ws-client/src/options/index.js b/packages/ws-client/src/options/index.js index 94d271c7..b1ca0834 100644 --- a/packages/ws-client/src/options/index.js +++ b/packages/ws-client/src/options/index.js @@ -1,14 +1,7 @@ // create options -import { - createConfig, - checkConfigAsync, - isContract, - isNotEmpty -} from 'jsonql-params-validator' -import { - JsonqlValidationError, - JsonqlCheckerError -} from 'jsonql-errors' +import { createConfig, checkConfigAsync, isNotEmpty } from 'jsonql-params-validator' +import { isContract } from 'jsonql-utils' +import { JsonqlValidationError, JsonqlCheckerError } from 'jsonql-errors' import { STRING_TYPE, BOOLEAN_TYPE, -- Gitee From c6379326299ab06f24eefc70131fd33cb55e389d Mon Sep 17 00:00:00 2001 From: joelchu Date: Tue, 15 Oct 2019 23:00:32 +0800 Subject: [PATCH 13/24] Fix all the basic module mapping problems --- packages/ws-client/src/api.js | 12 ++++++------ .../fixtures/beta/src/utils/process-contract.js | 2 +- .../tests/fixtures/beta/src/ws/ws-main-handler.js | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/ws-client/src/api.js b/packages/ws-client/src/api.js index 9d44e92d..fae45ca0 100644 --- a/packages/ws-client/src/api.js +++ b/packages/ws-client/src/api.js @@ -1,6 +1,7 @@ // the top level API // The goal is to create a generic method that will able to handle // any kind of clients +// import { injectToFn } from 'jsonql-utils' import generator from './core/generator' import checkOptions from './options' import { ee, processContract } from './utils' @@ -10,11 +11,11 @@ import { ee, processContract } from './utils' * @return {object} the wsClient instance with all the available API */ export default function wsClient(socketClientResolver) { - const { eventEmitter } = opts; // we need to inject property to this client later // therefore we need to do it this way - const _wsClient = (opts) => ( - checkOptions(opts) + return (opts) => { + const { eventEmitter } = opts; + return checkOptions(opts) .then(opts => ({ opts, nspMap: processContract(opts), @@ -23,13 +24,12 @@ export default function wsClient(socketClientResolver) { .then( ({opts, nspMap, ee}) => socketClientResolver(opts, nspMap, ee) ) - // @TODO the generator should be part of the http client .then( ({opts, nspMap, ee}) => generator(opts, nspMap, ee) ) .catch(err => { console.error(`jsonql-ws-client init error`, err) }) - ) - return injectToFn(_wsClient, 'CLIENT_TYPE_INFO', opts.serverType) + } + // return injectToFn(_wsClient, 'CLIENT_TYPE_INFO', opts.serverType) } diff --git a/packages/ws-client/tests/fixtures/beta/src/utils/process-contract.js b/packages/ws-client/tests/fixtures/beta/src/utils/process-contract.js index 7ec6a855..96c3038a 100644 --- a/packages/ws-client/tests/fixtures/beta/src/utils/process-contract.js +++ b/packages/ws-client/tests/fixtures/beta/src/utils/process-contract.js @@ -1,7 +1,7 @@ // mapping the resolver to their respective nsp import { JSONQL_PATH } from 'jsonql-constants' -import { groupByNamespace } from 'jsonql-jwt' +import { groupByNamespace } from 'jsonql-utils' import { JsonqlResolverNotFoundError } from 'jsonql-errors' import { MISSING_PROP_ERR } from './constants' diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js index 73b7582b..09109a14 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js @@ -15,7 +15,7 @@ import { } from 'jsonql-constants' import extractWsPayload from './extract-ws-payload' -import { createQueryStr } from 'jsonql-params-validator' +import { createQueryStr } from 'jsonql-utils' import { getDebug, createEvt } from '../utils' const debugFn = getDebug('ws-main-handler') -- Gitee From c69988395d4a63fe8a464688c26192046490d5f3 Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 16 Oct 2019 15:02:16 +0800 Subject: [PATCH 14/24] The base ws client is working correctly --- .../tests/fixtures/beta/src/ws/create-client.js | 2 +- packages/ws-client/tests/test-node.test.js | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js index d026e70c..db25986a 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js @@ -1,5 +1,5 @@ // make this another standalone module -import { getNameFromPayload } from 'jsonql-params-validator' +import { getNameFromPayload } from 'jsonql-utils' import { LOGIN_EVENT_NAME, LOGOUT_EVENT_NAME, JS_WS_NAME } from 'jsonql-constants' import { nspClient, nspAuthClient } from '../utils/create-nsp-client' // this become the cb diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index a9d1f095..043ac0b0 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -8,7 +8,8 @@ const fsx = require('fs-extra') const serverSetup = require('./fixtures/server-setup') const genToken = require('./fixtures/token') -const jsonqlWsClient = require('./fixtures/jsonql-ws-client') +const jsonqlWsClient = require('./fixtures/jsonql-ws-client') +const wsClient = jsonqlWsClient.default const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) @@ -19,13 +20,6 @@ const token = genToken(payload) const port = 8010; const url = `ws://localhost:${port}` -/* -const { - chainCreateNsps, - clientGenerator, - es -} = require('./fixtures/node') -*/ /// PREPARE TEST /// test.before(async t => { const { io, app } = await serverSetup({ @@ -39,7 +33,8 @@ test.before(async t => { t.context.server = app.listen(port) - t.context.client = jsonqlWsClient({ + t.context.client = wsClient({ + contract, hostname: url, serverType: JS_WS_NAME }) -- Gitee From 4ccc0fb20332de3fa9803b75e893c4391879c4b7 Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 16 Oct 2019 15:45:17 +0800 Subject: [PATCH 15/24] generator trap the call but it never reaches the actual call server part --- packages/ws-client/README.md | 19 +-- .../beta/src/utils/create-nsp-client.js | 3 +- .../fixtures/beta/src/ws/create-client.js | 6 +- .../beta/src/ws/extract-ws-payload.js | 3 - .../fixtures/beta/src/ws/ws-main-handler.js | 4 +- .../resolvers/socket/public/pinging.js | 6 +- packages/ws-client/tests/test-node.test.js | 141 ++---------------- 7 files changed, 32 insertions(+), 150 deletions(-) diff --git a/packages/ws-client/README.md b/packages/ws-client/README.md index 1155456f..eb41bc49 100644 --- a/packages/ws-client/README.md +++ b/packages/ws-client/README.md @@ -1,21 +1,16 @@ # jsonql-ws-client -This is for WebSocket client, all the core functionality moved to the jsonql-ws-base -for re-use and further develop other client / servers. +This module is **NOT** for direct use within your project. This is the foundation of all the +framework specific web socket (like) modules. -This is mainly for use within the node client as a MQTT like interface. And this is more intend -to use in combination with the [jsonql-node-client](https://npmjs.com/package/jsonql-node-client) +Please check the following -## Others +- [@jsonql/ws](https://npmjs.com/package/@jsonql/ws) for [WebSocket](https://npmjs.com/package/ws) client / server +- [@jsonql/socketio](https://npmjs.com/package/@jsonql/socketio) for [Socket.io](https://npmjs.com/package/socketio) client / server +- ~~@jsonql/primus for Primus client / server~~ (planning stage) -We have break up all the jsonql socket client / server in several modules -- ~~@jsonql/ws for WebSocket client / server~~ We keep the [jsonql-ws-server](https://npmjs.com/package/jsonql-ws-server) -- @jsonql/socketio for Socket.io client / server -- @jsonql/primus for Primus client / server - - -Please check [jsonql.org](https://jsonql.js.org) for further information +Please check [jsonql.org](https://jsonql.org) for further information --- diff --git a/packages/ws-client/tests/fixtures/beta/src/utils/create-nsp-client.js b/packages/ws-client/tests/fixtures/beta/src/utils/create-nsp-client.js index 9b656813..2bbca6cd 100644 --- a/packages/ws-client/tests/fixtures/beta/src/utils/create-nsp-client.js +++ b/packages/ws-client/tests/fixtures/beta/src/utils/create-nsp-client.js @@ -2,8 +2,7 @@ // pre-defined in the client-generator // and this one will have the same parameters // and the callback is identical -import getDebug from './get-debug' -const debugFn = getDebug('create-nsp-client') + /** * wrapper method to create a nsp without login * @param {string|boolean} namespace namespace url could be false diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js index db25986a..dbd12eb8 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/create-client.js @@ -7,8 +7,10 @@ import clientEventHandler from '../client-event-handler' import triggerNamespacesOnError from '../utils/trigger-namespaces-on-error' // move this up one level from client-event-handler import wsMainHandler from './ws-main-handler' -import { getDebug, clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils' -const debugFn = getDebug('ws-create-client') +import { clearMainEmitEvt, getNamespaceInOrder, disconnect } from '../utils' +import debug from 'debug' + +const debugFn = debug('jsonql-ws-client:ws-create-client') /** * Because the nsps can be throw away so it doesn't matter the scope diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/extract-ws-payload.js b/packages/ws-client/tests/fixtures/beta/src/ws/extract-ws-payload.js index 1a8412ba..e223ed47 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/extract-ws-payload.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/extract-ws-payload.js @@ -3,9 +3,6 @@ import { WS_EVT_NAME, WS_DATA_NAME, WS_REPLY_TYPE } from 'jsonql-constants' import { isString, isKeyInObject } from 'jsonql-params-validator' import { JsonqlError, clientErrorsHandler } from 'jsonql-errors' -import getDebug from '../utils/get-debug' -const debugFn = getDebug('extract-ws-payload') - const keys = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ] /** diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js index 09109a14..8939ef20 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js @@ -18,7 +18,9 @@ import extractWsPayload from './extract-ws-payload' import { createQueryStr } from 'jsonql-utils' import { getDebug, createEvt } from '../utils' -const debugFn = getDebug('ws-main-handler') +import debug from 'debug' + +const debugFn = debug('jsonql-ws-client:ws-main-handler') /** * under extremely circumstances we might not even have a resolverName, then diff --git a/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js b/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js index 2cf07351..82160f2a 100644 --- a/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js +++ b/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js @@ -1,10 +1,13 @@ // this is a public method always avaialble +const debug = require('debug')('jsonql-ws-client:resolver:pinging') + let ctn = 0; /** * @param {string} msg message * @return {string} reply message based on your message */ module.exports = function pinging(msg) { + debug(`got call with --> ${msg}`) if (ctn > 0) { switch (msg) { case 'ping': @@ -12,11 +15,12 @@ module.exports = function pinging(msg) { case 'pong': pinging.send = 'ping'; default: - return; + return `Got your message ${msg}`; //pinging.send = 'You lose!'; } return; } ++ctn; + debug(`Did return here`) return 'connection established'; } diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index 043ac0b0..78de4dfe 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -33,151 +33,34 @@ test.before(async t => { t.context.server = app.listen(port) - t.context.client = wsClient({ + t.context.client = await wsClient({ contract, hostname: url, - serverType: JS_WS_NAME + serverType: JS_WS_NAME, + enableAuth: true }) }) // real test start here -test.serial.only('It should able to replace the same event with new method', t => { +test.serial('It should able to create the WebSocket client object', t => { const client = t.context.client; - - debug(client) - - t.pass() - + t.truthy(client) }) -test.serial.cb('It should able to resolve the promise one after the other', t => { +test.serial.cb('The ws client can connect to the WebSocket server public interface', t => { t.plan(1) - let opts = t.context.opts; - let p1 = () => opts.nspAuthClient([url, 'jsonql/private'].join('/'), token) - let p2 = () => opts.nspClient([url, 'jsonql/public'].join('/')) - /* - let p1 = () => new Promise(resolver => { - setTimeout(() => { - resolver('first') - }, 1000) - }) - let p2 = () => new Promise(resolver => { resolver('second') }) - */ - chainCreateNsps([ - p1(), p2() - ]).then(results => { - debug(results) - t.pass() - t.end() - }) -}) - -test.serial.cb('Just test with the ws client can connect to the server normally', t => { - t.plan(2) - let opts = t.context.opts; - // t.truthy(opts.nspClient) - // t.truthy(opts.nspAuthClient) - - opts.nspAuthClient([url, 'jsonql/private'].join('/'), token) - .then(socket => { - debug('io1 pass') - t.pass() - opts.nspClient([url, 'jsonql/public'].join('/')) - .then( socket => { - debug('io2 pass') - t.pass() - t.end() - }) - }) - - /* - this was for ws - ws1.onopen = function() { - t.pass() - debug('ws1 connected') - } - ws2.onopen = function() { - t.pass() - debug('ws2 connected') - ws1.terminate() - ws2.terminate() - t.end() - } - */ -}) - - -test.serial.cb('It should able to use the chainCreateNsps to run connection in sequence', t => { - t.plan(1) - let opts = t.context.opts; + const client = t.context.client; - // t.truthy(opts.nspClientAsync) - // t.truthy(opts.nspAuthClientAsync) + client.pinging('ping') + .then(msg => { + // @NOTE perhaps I should consider when return the + // the promise, I could also return the socket object for use as well - opts.nspAuthClientAsync([url, 'jsonql/private'].join('/'), token) - .then(ws => { + debug(msg) t.pass() t.end() }) - - // the bug is the chainCreateNsps somehow when we put it in there - // the connection just hang - - /* - chainCreateNsps([ - opts.nspAuthClientAsync([url, 'jsonql/private'].join('/'), token), - // opts.nspClientAsync([url, 'jsonql/public'].join('/')) - ]).then(nsps => { - t.is(nsps.length, 2) - nsps.forEach(nsp => { - nsp.terminate() - }) - t.end() - }) - */ -}) - -test.serial.cb.skip('It should able to wrap the connect call with the onopen callback', t => { - t.plan(3) - let opts = t.context.opts; - let ee = t.context.ee; - let publicConnect = () => { - return opts.nspClientAsync([url, 'jsonql/public'].join('/')) - .then(ws => { - ws.onopen = function() { - ee.$trigger('onReady1', ws) - } - return 'jsonql/public' - }) - } - - let privateConnect = () => { - return opts.nspAuthClientAsync([url, 'jsonql/private'].join('/'), token) - .then(ws => { - ws.onopen = function() { - ee.$trigger('onReady2', ws) - } - return 'jsonql/private' - }) - } - - chainCreateNsps([ - privateConnect(), - publicConnect() - ]).then(namespaces => { - t.is(namespaces.length, 2) - }) - - ee.$on('onReady1', function() { - t.pass() - t.end() - }) - - ee.$on('onReady2', function() { - t.pass() - }) - }) -- Gitee From 780b3312d215e75a21ba83450e2685e365139f0b Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 16 Oct 2019 15:47:12 +0800 Subject: [PATCH 16/24] remove the unused code to make it clear to find what I am looking for --- .../ws-client/src/node/client-generator.js | 53 - packages/ws-client/src/node/main.cjs.js | 7691 ----------------- 2 files changed, 7744 deletions(-) delete mode 100644 packages/ws-client/src/node/client-generator.js delete mode 100644 packages/ws-client/src/node/main.cjs.js diff --git a/packages/ws-client/src/node/client-generator.js b/packages/ws-client/src/node/client-generator.js deleted file mode 100644 index 788a3153..00000000 --- a/packages/ws-client/src/node/client-generator.js +++ /dev/null @@ -1,53 +0,0 @@ -// client generator for node.js - -// @TODO move this out of the jsonql-jwt -/* -const { - socketIoNodeHandshakeLogin, - socketIoNodeRoundtripLogin, - socketIoNodeClientAsync -} = require('./socketio-client') - -const { - wsNodeClient, - wsNodeAuthClient -} = require('./ws-client') -*/ - -const { chainPromises } = require('jsonql-jwt') - -const { JsonqlError } = require('jsonql-errors') -const { JS_WS_SOCKET_IO_NAME, JS_WS_NAME } = require('jsonql-constants') -const { isString } = require('jsonql-params-validator') -const debug = require('debug')('jsonql-ws-client:client-generator:cjs') - -/** - * @TODO we have taken out all the socket client to their respective package - * now we need to figure out how to inject them back into this client generator - * websocket client generator - * @param {object} payload with opts, nspMap, ee - * @return {object} same just mutate it - */ -const clientGenerator = ({ opts, nspMap, ee }) => { - // debug(nspMap) - switch (opts.serverType) { - case JS_WS_SOCKET_IO_NAME: - // the socket.io normal client is not Promise so we make them all the same - opts.nspClient = socketIoNodeClientAsync; - // (...args) => Promise.resolve(Reflect.apply(socketIoNodeClient, null, args)) - // we also need to determine the type of socket.io login here - opts.nspAuthClient = isString(opts.useJwt) ? socketIoNodeRoundtripLogin : socketIoNodeHandshakeLogin; - // debug(opts.nspAuthClient) - break; - case JS_WS_NAME: - opts.nspClient = wsNodeClient; - opts.nspAuthClient = wsNodeAuthClient; - break; - default: - throw new JsonqlError(`Unknown serverType: ${opts.serverType}`) - } - return { opts, nspMap, ee } -} - -// export it -module.exports = clientGenerator; diff --git a/packages/ws-client/src/node/main.cjs.js b/packages/ws-client/src/node/main.cjs.js deleted file mode 100644 index f5a8e6ae..00000000 --- a/packages/ws-client/src/node/main.cjs.js +++ /dev/null @@ -1,7691 +0,0 @@ -'use strict'; - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var debug$2 = _interopDefault(require('debug')); - -/** - * This is a custom error to throw when server throw a 406 - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var Jsonql406Error = /*@__PURE__*/(function (Error) { - function Jsonql406Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - // We can't access the static name from an instance - // but we can do it like this - this.className = Jsonql406Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql406Error); - } - } - - if ( Error ) Jsonql406Error.__proto__ = Error; - Jsonql406Error.prototype = Object.create( Error && Error.prototype ); - Jsonql406Error.prototype.constructor = Jsonql406Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 406; - }; - - staticAccessors.name.get = function () { - return 'Jsonql406Error'; - }; - - Object.defineProperties( Jsonql406Error, staticAccessors ); - - return Jsonql406Error; -}(Error)); - -/** - * This is a custom error to throw when server throw a 500 - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var Jsonql500Error = /*@__PURE__*/(function (Error) { - function Jsonql500Error() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = Jsonql500Error.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, Jsonql500Error); - } - } - - if ( Error ) Jsonql500Error.__proto__ = Error; - Jsonql500Error.prototype = Object.create( Error && Error.prototype ); - Jsonql500Error.prototype.constructor = Jsonql500Error; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'Jsonql500Error'; - }; - - Object.defineProperties( Jsonql500Error, staticAccessors ); - - return Jsonql500Error; -}(Error)); - -/** - * This is a custom error to throw when pass credential but fail - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var JsonqlAuthorisationError = /*@__PURE__*/(function (Error) { - function JsonqlAuthorisationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlAuthorisationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlAuthorisationError); - } - } - - if ( Error ) JsonqlAuthorisationError.__proto__ = Error; - JsonqlAuthorisationError.prototype = Object.create( Error && Error.prototype ); - JsonqlAuthorisationError.prototype.constructor = JsonqlAuthorisationError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlAuthorisationError'; - }; - - Object.defineProperties( JsonqlAuthorisationError, staticAccessors ); - - return JsonqlAuthorisationError; -}(Error)); - -/** - * This is a custom error when not supply the credential and try to get contract - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var JsonqlContractAuthError = /*@__PURE__*/(function (Error) { - function JsonqlContractAuthError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlContractAuthError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlContractAuthError); - } - } - - if ( Error ) JsonqlContractAuthError.__proto__ = Error; - JsonqlContractAuthError.prototype = Object.create( Error && Error.prototype ); - JsonqlContractAuthError.prototype.constructor = JsonqlContractAuthError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 401; - }; - - staticAccessors.name.get = function () { - return 'JsonqlContractAuthError'; - }; - - Object.defineProperties( JsonqlContractAuthError, staticAccessors ); - - return JsonqlContractAuthError; -}(Error)); - -/** - * This is a custom error to throw when the resolver throw error and capture inside the middleware - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var JsonqlResolverAppError = /*@__PURE__*/(function (Error) { - function JsonqlResolverAppError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlResolverAppError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverAppError); - } - } - - if ( Error ) JsonqlResolverAppError.__proto__ = Error; - JsonqlResolverAppError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverAppError.prototype.constructor = JsonqlResolverAppError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 500; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverAppError'; - }; - - Object.defineProperties( JsonqlResolverAppError, staticAccessors ); - - return JsonqlResolverAppError; -}(Error)); - -/** - * This is a custom error to throw when could not find the resolver - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var JsonqlResolverNotFoundError = /*@__PURE__*/(function (Error) { - function JsonqlResolverNotFoundError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlResolverNotFoundError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlResolverNotFoundError); - } - } - - if ( Error ) JsonqlResolverNotFoundError.__proto__ = Error; - JsonqlResolverNotFoundError.prototype = Object.create( Error && Error.prototype ); - JsonqlResolverNotFoundError.prototype.constructor = JsonqlResolverNotFoundError; - - var staticAccessors = { statusCode: { configurable: true },name: { configurable: true } }; - - staticAccessors.statusCode.get = function () { - return 404; - }; - - staticAccessors.name.get = function () { - return 'JsonqlResolverNotFoundError'; - }; - - Object.defineProperties( JsonqlResolverNotFoundError, staticAccessors ); - - return JsonqlResolverNotFoundError; -}(Error)); - -// this get throw from within the checkOptions when run through the enum failed -var JsonqlEnumError = /*@__PURE__*/(function (Error) { - function JsonqlEnumError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlEnumError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlEnumError); - } - } - - if ( Error ) JsonqlEnumError.__proto__ = Error; - JsonqlEnumError.prototype = Object.create( Error && Error.prototype ); - JsonqlEnumError.prototype.constructor = JsonqlEnumError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlEnumError'; - }; - - Object.defineProperties( JsonqlEnumError, staticAccessors ); - - return JsonqlEnumError; -}(Error)); - -// this will throw from inside the checkOptions -var JsonqlTypeError = /*@__PURE__*/(function (Error) { - function JsonqlTypeError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlTypeError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlTypeError); - } - } - - if ( Error ) JsonqlTypeError.__proto__ = Error; - JsonqlTypeError.prototype = Object.create( Error && Error.prototype ); - JsonqlTypeError.prototype.constructor = JsonqlTypeError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlTypeError'; - }; - - Object.defineProperties( JsonqlTypeError, staticAccessors ); - - return JsonqlTypeError; -}(Error)); - -// allow supply a custom checker function -// if that failed then we throw this error -var JsonqlCheckerError = /*@__PURE__*/(function (Error) { - function JsonqlCheckerError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlCheckerError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlCheckerError); - } - } - - if ( Error ) JsonqlCheckerError.__proto__ = Error; - JsonqlCheckerError.prototype = Object.create( Error && Error.prototype ); - JsonqlCheckerError.prototype.constructor = JsonqlCheckerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlCheckerError'; - }; - - Object.defineProperties( JsonqlCheckerError, staticAccessors ); - - return JsonqlCheckerError; -}(Error)); - -// custom validation error class -// when validaton failed -var JsonqlValidationError = /*@__PURE__*/(function (Error) { - function JsonqlValidationError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlValidationError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlValidationError); - } - } - - if ( Error ) JsonqlValidationError.__proto__ = Error; - JsonqlValidationError.prototype = Object.create( Error && Error.prototype ); - JsonqlValidationError.prototype.constructor = JsonqlValidationError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlValidationError'; - }; - - Object.defineProperties( JsonqlValidationError, staticAccessors ); - - return JsonqlValidationError; -}(Error)); - -// the core stuff to id if it's calling with jsonql -var DATA_KEY = 'data'; -var ERROR_KEY = 'error'; - -var JSONQL_PATH = 'jsonql'; -var DEFAULT_TYPE = 'any'; - -// @TODO remove this is not in use -// export const CLIENT_CONFIG_FILE = '.clients.json'; -// export const CONTRACT_CONFIG_FILE = 'jsonql-contract-config.js'; -// type of resolvers -var QUERY_NAME = 'query'; -var MUTATION_NAME = 'mutation'; -var SOCKET_NAME = 'socket'; -var QUERY_ARG_NAME = 'args'; -// for contract-cli -var KEY_WORD = 'continue'; - -var TYPE_KEY = 'type'; -var OPTIONAL_KEY = 'optional'; -var ENUM_KEY = 'enumv'; // need to change this because enum is a reserved word -var ARGS_KEY = 'args'; -var CHECKER_KEY = 'checker'; -var ALIAS_KEY = 'alias'; -var LOGIN_NAME = 'login'; -var ISSUER_NAME = LOGIN_NAME; // legacy issue need to replace them later -var LOGOUT_NAME = 'logout'; - -var OR_SEPERATOR = '|'; - -var STRING_TYPE = 'string'; -var BOOLEAN_TYPE = 'boolean'; -var ARRAY_TYPE = 'array'; -var OBJECT_TYPE = 'object'; - -var NUMBER_TYPE = 'number'; -var ARRAY_TYPE_LFT = 'array.<'; -var ARRAY_TYPE_RGT = '>'; - -var NO_ERROR_MSG = 'No message'; -var NO_STATUS_CODE = -1; -var LOGIN_EVENT_NAME = '__login__'; -var LOGOUT_EVENT_NAME = '__logout__'; - -// for ws servers -var WS_REPLY_TYPE = '__reply__'; -var WS_EVT_NAME = '__event__'; -var WS_DATA_NAME = '__data__'; -var EMIT_REPLY_TYPE = 'emit'; -var ACKNOWLEDGE_REPLY_TYPE = 'acknowledge'; -var ERROR_TYPE = 'error'; - -var JS_WS_SOCKET_IO_NAME = 'socket.io'; -var JS_WS_NAME = 'ws'; - -// for ws client -var MESSAGE_PROP_NAME = 'onMessage'; -var RESULT_PROP_NAME = 'onResult'; -var ERROR_PROP_NAME = 'onError'; -var READY_PROP_NAME = 'onReady'; -var SEND_MSG_PROP_NAME = 'send'; -var NOT_LOGIN_ERR_MSG = 'NOT LOGIN'; -var HSA_ALGO = 'HS256'; - -/** - * This is a custom error to throw whenever a error happen inside the jsonql - * This help us to capture the right error, due to the call happens in sequence - * @param {string} message to tell what happen - * @param {mixed} extra things we want to add, 500? - */ -var JsonqlError = /*@__PURE__*/(function (Error) { - function JsonqlError() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - Error.apply(this, args); - - this.message = args[0]; - this.detail = args[1]; - - this.className = JsonqlError.name; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, JsonqlError); - } - } - - if ( Error ) JsonqlError.__proto__ = Error; - JsonqlError.prototype = Object.create( Error && Error.prototype ); - JsonqlError.prototype.constructor = JsonqlError; - - var staticAccessors = { name: { configurable: true },statusCode: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlError'; - }; - - staticAccessors.statusCode.get = function () { - return NO_STATUS_CODE; - }; - - Object.defineProperties( JsonqlError, staticAccessors ); - - return JsonqlError; -}(Error)); - -// this is from an example from Koa team to use for internal middleware ctx.throw -// but after the test the res.body part is unable to extract the required data -// I keep this one here for future reference - -var JsonqlServerError = /*@__PURE__*/(function (Error) { - function JsonqlServerError(statusCode, message) { - Error.call(this, message); - this.statusCode = statusCode; - this.className = JsonqlServerError.name; - } - - if ( Error ) JsonqlServerError.__proto__ = Error; - JsonqlServerError.prototype = Object.create( Error && Error.prototype ); - JsonqlServerError.prototype.constructor = JsonqlServerError; - - var staticAccessors = { name: { configurable: true } }; - - staticAccessors.name.get = function () { - return 'JsonqlServerError'; - }; - - Object.defineProperties( JsonqlServerError, staticAccessors ); - - return JsonqlServerError; -}(Error)); - -/** - * this will put into generator call at the very end and catch - * the error throw from inside then throw again - * this is necessary because we split calls inside and the throw - * will not reach the actual client unless we do it this way - * @param {object} e Error - * @return {void} just throw - */ -function finalCatch(e) { - // this is a hack to get around the validateAsync not actually throw error - // instead it just rejected it with the array of failed parameters - if (Array.isArray(e)) { - // if we want the message then I will have to create yet another function - // to wrap this function to provide the name prop - throw new JsonqlValidationError('', e); - } - var msg = e.message || NO_ERROR_MSG; - var detail = e.detail || e; - switch (true) { - case e instanceof Jsonql406Error: - throw new Jsonql406Error(msg, detail); - case e instanceof Jsonql500Error: - throw new Jsonql500Error(msg, detail); - case e instanceof JsonqlAuthorisationError: - throw new JsonqlAuthorisationError(msg, detail); - case e instanceof JsonqlContractAuthError: - throw new JsonqlContractAuthError(msg, detail); - case e instanceof JsonqlResolverAppError: - throw new JsonqlResolverAppError(msg, detail); - case e instanceof JsonqlResolverNotFoundError: - throw new JsonqlResolverNotFoundError(msg, detail); - case e instanceof JsonqlEnumError: - throw new JsonqlEnumError(msg, detail); - case e instanceof JsonqlTypeError: - throw new JsonqlTypeError(msg, detail); - case e instanceof JsonqlCheckerError: - throw new JsonqlCheckerError(msg, detail); - case e instanceof JsonqlValidationError: - throw new JsonqlValidationError(msg, detail); - case e instanceof JsonqlServerError: - throw new JsonqlServerError(msg, detail); - default: - throw new JsonqlError(msg, detail); - } -} - -var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Built-in value references. */ -var Symbol = root.Symbol; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag$1 = Symbol ? Symbol.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag$1 && symToStringTag$1 in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ -function identity(value) { - return value; -} - -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} - -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; - -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); - -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} - -/** Used for built-in method references. */ -var funcProto = Function.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} - -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Used for built-in method references. */ -var funcProto$1 = Function.prototype, - objectProto$2 = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString$1 = funcProto$1.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); - -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); -} - -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} - -/* Built-in method references that are verified to be native. */ -var WeakMap$1 = getNative(root, 'WeakMap'); - -/** Built-in value references. */ -var objectCreate = Object.create; - -/** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ -var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; -}()); - -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} - -/** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ -function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; -} - -/** Used to detect hot functions by number of calls within a span of milliseconds. */ -var HOT_COUNT = 800, - HOT_SPAN = 16; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeNow = Date.now; - -/** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ -function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; -} - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant(value) { - return function() { - return value; - }; -} - -var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} -}()); - -/** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); -}; - -/** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var setToString = shortOut(baseSetToString); - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } -} - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} - -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$2.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } -} - -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ -function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; -} - -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; -} - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; -} - -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} - -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4; - - return value === proto; -} - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} - -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$5.hasOwnProperty; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$3.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; - -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; -} - -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag$1 = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); - -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - -/** Used for built-in method references. */ -var objectProto$6 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$4.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); - -/** Used for built-in method references. */ -var objectProto$7 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$5.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} - -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$8 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty$6.call(object, key)))) { - result.push(key); - } - } - return result; -} - -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); -} - -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); -} - -/* Built-in method references that are verified to be native. */ -var nativeCreate = getNative(Object, 'create'); - -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; -} - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** Used for built-in method references. */ -var objectProto$9 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$7.call(data, key) ? data[key] : undefined; -} - -/** Used for built-in method references. */ -var objectProto$a = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$8 = objectProto$a.hasOwnProperty; - -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$8.call(data, key); -} - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; -} - -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; - this.size = 0; -} - -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; -} - -/** Used for built-in method references. */ -var arrayProto = Array.prototype; - -/** Built-in value references. */ -var splice = arrayProto.splice; - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; -} - -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; -} - -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} - -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} - -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; - -/* Built-in method references that are verified to be native. */ -var Map$1 = getNative(root, 'Map'); - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map$1 || ListCache), - 'string': new Hash - }; -} - -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} - -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} - -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} - -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} - -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; - -/** Error message constants. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ -function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; -} - -// Expose `MapCache`. -memoize.Cache = MapCache; - -/** Used as the maximum memoize cache size. */ -var MAX_MEMOIZE_SIZE = 500; - -/** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ -function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; -} - -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; - -/** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ -var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -}); - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ -function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); -} - -/** Used as references for various `Number` constants. */ -var INFINITY$1 = 1 / 0; - -/** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ -function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; -} - -/** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ -function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; -} - -/** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ -function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; -} - -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} - -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); - -/** `Object#toString` result references. */ -var objectTag$1 = '[object Object]'; - -/** Used for built-in method references. */ -var funcProto$2 = Function.prototype, - objectProto$b = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString$2 = funcProto$2.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty$9 = objectProto$b.hasOwnProperty; - -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString$2.call(Object); - -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag$1) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$9.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString$2.call(Ctor) == objectCtorString; -} - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']', - rsCombo = '[' + rsComboRange$1 + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange$1 + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange$1 + ']?', - rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ -function stackClear() { - this.__data__ = new ListCache; - this.size = 0; -} - -/** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; -} - -/** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function stackGet(key) { - return this.__data__.get(key); -} - -/** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function stackHas(key) { - return this.__data__.has(key); -} - -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; - -/** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ -function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; -} - -/** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; -} - -// Add methods to `Stack`. -Stack.prototype.clear = stackClear; -Stack.prototype['delete'] = stackDelete; -Stack.prototype.get = stackGet; -Stack.prototype.has = stackHas; -Stack.prototype.set = stackSet; - -/** Detect free variable `exports`. */ -var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; - -/** Built-in value references. */ -var Buffer$1 = moduleExports$2 ? root.Buffer : undefined, - allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined; - -/** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ -function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; -} - -/** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ -function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; -} - -/** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ -function stubArray() { - return []; -} - -/** Used for built-in method references. */ -var objectProto$c = Object.prototype; - -/** Built-in value references. */ -var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols = Object.getOwnPropertySymbols; - -/** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); -}; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols$1 = Object.getOwnPropertySymbols; - -/** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; -}; - -/** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ -function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); -} - -/** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); -} - -/** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); -} - -/* Built-in method references that are verified to be native. */ -var DataView = getNative(root, 'DataView'); - -/* Built-in method references that are verified to be native. */ -var Promise$1 = getNative(root, 'Promise'); - -/* Built-in method references that are verified to be native. */ -var Set$1 = getNative(root, 'Set'); - -/** `Object#toString` result references. */ -var mapTag$1 = '[object Map]', - objectTag$2 = '[object Object]', - promiseTag = '[object Promise]', - setTag$1 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - -var dataViewTag$1 = '[object DataView]'; - -/** Used to detect maps, sets, and weakmaps. */ -var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map$1), - promiseCtorString = toSource(Promise$1), - setCtorString = toSource(Set$1), - weakMapCtorString = toSource(WeakMap$1); - -/** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -var getTag = baseGetTag; - -// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. -if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) || - (Map$1 && getTag(new Map$1) != mapTag$1) || - (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || - (Set$1 && getTag(new Set$1) != setTag$1) || - (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag$2 ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$1; - case mapCtorString: return mapTag$1; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$1; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; -} - -var getTag$1 = getTag; - -/** Built-in value references. */ -var Uint8Array = root.Uint8Array; - -/** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ -function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; -} - -/** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ -function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); -} - -/** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; -} - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; -} - -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} - -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } -} - -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; - -/** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ -function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; -} - -/** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - -/** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ -function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; -} - -/** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ -function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; -} - -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - -/** `Object#toString` result references. */ -var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$2 = '[object Map]', - numberTag$1 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$2 = '[object Set]', - stringTag$1 = '[object String]', - symbolTag$1 = '[object Symbol]'; - -var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$2 = '[object DataView]'; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto$1 = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - -/** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$2: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$1: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$1: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$2: - var convert = mapToArray; - - case setTag$2: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; -} - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$2 = 1; - -/** Used for built-in method references. */ -var objectProto$d = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$a = objectProto$d.hasOwnProperty; - -/** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; -} - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$3 = 1; - -/** `Object#toString` result references. */ -var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$3 = '[object Object]'; - -/** Used for built-in method references. */ -var objectProto$e = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$b = objectProto$e.hasOwnProperty; - -/** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag$1 : getTag$1(object), - othTag = othIsArr ? arrayTag$1 : getTag$1(other); - - objTag = objTag == argsTag$2 ? objectTag$3 : objTag; - othTag = othTag == argsTag$2 ? objectTag$3 : othTag; - - var objIsObj = objTag == objectTag$3, - othIsObj = othTag == objectTag$3, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$b.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); -} - -/** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ -function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); -} - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - -/** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ -function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; -} - -/** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ -function isStrictComparable(value) { - return value === value && !isObject(value); -} - -/** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ -function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; -} - -/** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ -function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; -} - -/** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; -} - -/** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ -function baseHasIn(object, key) { - return object != null && key in Object(object); -} - -/** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ -function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); -} - -/** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ -function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); -} - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - -/** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; -} - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} - -/** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; -} - -/** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ -function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); -} - -/** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ -function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); -} - -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} - -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); - -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); -} - -/** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } -} - -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} - -/** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; -} - -/** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ -function toPlainObject(value) { - return copyObject(value, keysIn(value)); -} - -/** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ -function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); -} - -/** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ -function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); -} - -/** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ -function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; -} - -/** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ -function findKey(object, predicate) { - return baseFindKey(object, baseIteratee(predicate), baseForOwn); -} - -/** `Object#toString` result references. */ -var stringTag$2 = '[object String]'; - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag$2); -} - -/** `Object#toString` result references. */ -var boolTag$2 = '[object Boolean]'; - -/** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ -function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag$2); -} - -/** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ -function isEqual(value, other) { - return baseIsEqual(value, other); -} - -/** `Object#toString` result references. */ -var numberTag$2 = '[object Number]'; - -/** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ -function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag$2); -} - -/** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ -function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; -} - -/** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ -function isNull(value) { - return value === null; -} - -/** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ -function isUndefined(value) { - return value === undefined; -} - -/** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ -function mapKeys(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; -} - -/** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ -function mapValues(object, iteratee) { - var result = {}; - iteratee = baseIteratee(iteratee); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; -} - -/** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ -var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); -}); - -/** Error message constants. */ -var FUNC_ERROR_TEXT$1 = 'Expected a function'; - -/** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ -function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT$1); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; -} - -/** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ -function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; -} - -/** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ -function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; -} - -/** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ -function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); -} - -/** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ -function omitBy(object, predicate) { - return pickBy(object, negate(baseIteratee(predicate))); -} - -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); -} - -/** - * Check several parameter that there is something in the param - * @param {*} param input - * @return {boolean} - */ - -function notEmpty (a) { - if (isArray(a)) { - return true; - } - return a !== undefined && a !== null && trim(a) !== ''; -} - -// validator numbers -/** - * @2015-05-04 found a problem if the value is a number like string - * it will pass, so add a check if it's string before we pass to next - * @param {number} value expected value - * @return {boolean} true if OK - */ -var checkIsNumber = function(value) { - return isString(value) ? false : !isNaN( parseFloat(value) ) -}; - -// validate string type -/** - * @param {string} value expected value - * @return {boolean} true if OK - */ -var checkIsString = function(value) { - return (trim(value) !== '') ? isString(value) : false; -}; - -// check for boolean -/** - * @param {boolean} value expected - * @return {boolean} true if OK - */ -var checkIsBoolean = function(value) { - return isBoolean(value); -}; - -// validate any thing only check if there is something -/** - * @param {*} value the value - * @param {boolean} [checkNull=true] strict check if there is null value - * @return {boolean} true is OK - */ -var checkIsAny = function(value, checkNull) { - if ( checkNull === void 0 ) checkNull = true; - - if (!isUndefined(value) && value !== '' && trim(value) !== '') { - if (checkNull === false || (checkNull === true && !isNull(value))) { - return true; - } - } - return false; -}; - -// Good practice rule - No magic number - -var ARGS_NOT_ARRAY_ERR = "args is not an array! You might want to do: ES6 Array.from(arguments) or ES5 Array.prototype.slice.call(arguments)"; -var PARAMS_NOT_ARRAY_ERR = "params is not an array! Did something gone wrong when you generate the contract.json?"; -var EXCEPTION_CASE_ERR = 'Could not understand your arguments and parameter structure!'; -// @TODO the jsdoc return array. and we should also allow array syntax -var DEFAULT_TYPE$1 = DEFAULT_TYPE; -var ARRAY_TYPE_LFT$1 = ARRAY_TYPE_LFT; -var ARRAY_TYPE_RGT$1 = ARRAY_TYPE_RGT; - -var TYPE_KEY$1 = TYPE_KEY; -var OPTIONAL_KEY$1 = OPTIONAL_KEY; -var ENUM_KEY$1 = ENUM_KEY; -var ARGS_KEY$1 = ARGS_KEY; -var CHECKER_KEY$1 = CHECKER_KEY; -var ALIAS_KEY$1 = ALIAS_KEY; - -var ARRAY_TYPE$1 = ARRAY_TYPE; -var OBJECT_TYPE$1 = OBJECT_TYPE; -var STRING_TYPE$1 = STRING_TYPE; -var BOOLEAN_TYPE$1 = BOOLEAN_TYPE; -var NUMBER_TYPE$1 = NUMBER_TYPE; -var KEY_WORD$1 = KEY_WORD; -var OR_SEPERATOR$1 = OR_SEPERATOR; - -// not actually in use -// export const NUMBER_TYPES = JSONQL_CONSTANTS.NUMBER_TYPES; - -// primitive types - -/** - * this is a wrapper method to call different one based on their type - * @param {string} type to check - * @return {function} a function to handle the type - */ -var combineFn = function(type) { - switch (type) { - case NUMBER_TYPE$1: - return checkIsNumber; - case STRING_TYPE$1: - return checkIsString; - case BOOLEAN_TYPE$1: - return checkIsBoolean; - default: - return checkIsAny; - } -}; - -// validate array type - -/** - * @param {array} value expected - * @param {string} [type=''] pass the type if we encounter array. then we need to check the value as well - * @return {boolean} true if OK - */ -var checkIsArray = function(value, type) { - if ( type === void 0 ) type=''; - - if (isArray(value)) { - if (type === '' || trim(type)==='') { - return true; - } - // we test it in reverse - // @TODO if the type is an array (OR) then what? - // we need to take into account this could be an array - var c = value.filter(function (v) { return !combineFn(type)(v); }); - return !(c.length > 0) - } - return false; -}; - -/** - * check if it matches the array. pattern - * @param {string} type - * @return {boolean|array} false means NO, always return array - */ -var isArrayLike$1 = function(type) { - // @TODO could that have something like array<> instead of array.<>? missing the dot? - // because type script is Array without the dot - if (type.indexOf(ARRAY_TYPE_LFT$1) > -1 && type.indexOf(ARRAY_TYPE_RGT$1) > -1) { - var _type = type.replace(ARRAY_TYPE_LFT$1, '').replace(ARRAY_TYPE_RGT$1, ''); - if (_type.indexOf(OR_SEPERATOR$1)) { - return _type.split(OR_SEPERATOR$1) - } - return [_type] - } - return false; -}; - -/** - * we might encounter something like array. then we need to take it apart - * @param {object} p the prepared object for processing - * @param {string|array} type the type came from - * @return {boolean} for the filter to operate on - */ -var arrayTypeHandler = function(p, type) { - var arg = p.arg; - // need a special case to handle the OR type - // we need to test the args instead of the type(s) - if (type.length > 1) { - return !arg.filter(function (v) { return ( - !(type.length > type.filter(function (t) { return !combineFn(t)(v); }).length) - ); }).length; - } - // type is array so this will be or! - return type.length > type.filter(function (t) { return !checkIsArray(arg, t); }).length; -}; - -// validate object type -/** - * @TODO if provide with the keys then we need to check if the key:value type as well - * @param {object} value expected - * @param {array} [keys=null] if it has the keys array to compare as well - * @return {boolean} true if OK - */ -var checkIsObject = function(value, keys) { - if ( keys === void 0 ) keys=null; - - if (isPlainObject(value)) { - if (!keys) { - return true; - } - if (checkIsArray(keys)) { - // please note we DON'T care if some is optional - // plese refer to the contract.json for the keys - return !keys.filter(function (key) { - var _value = value[key.name]; - return !(key.type.length > key.type.filter(function (type) { - var tmp; - if (!isUndefined(_value)) { - if ((tmp = isArrayLike$1(type)) !== false) { - return !arrayTypeHandler({arg: _value}, tmp) - // return tmp.filter(t => !checkIsArray(_value, t)).length; - // @TODO there might be an object within an object with keys as well :S - } - return !combineFn(type)(_value) - } - return true; - }).length) - }).length; - } - } - return false; -}; - -/** - * fold this into it's own function to handler different object type - * @param {object} p the prepared object for process - * @return {boolean} - */ -var objectTypeHandler = function(p) { - var arg = p.arg; - var param = p.param; - var _args = [arg]; - if (Array.isArray(param.keys) && param.keys.length) { - _args.push(param.keys); - } - // just simple check - return checkIsObject.apply(null, _args) -}; - -// move the index.js code here that make more sense to find where things are - -// import debug from 'debug' -// const debugFn = debug('jsonql-params-validator:validator') -// also export this for use in other places - -/** - * We need to handle those optional parameter without a default value - * @param {object} params from contract.json - * @return {boolean} for filter operation false is actually OK - */ -var optionalHandler = function( params ) { - var arg = params.arg; - var param = params.param; - if (notEmpty(arg)) { - // debug('call optional handler', arg, params); - // loop through the type in param - return !(param.type.length > param.type.filter(function (type) { return validateHandler(type, params); } - ).length) - } - return false; -}; - -/** - * actually picking the validator - * @param {*} type for checking - * @param {*} value for checking - * @return {boolean} true on OK - */ -var validateHandler = function(type, value) { - var tmp; - switch (true) { - case type === OBJECT_TYPE$1: - // debugFn('call OBJECT_TYPE') - return !objectTypeHandler(value) - case type === ARRAY_TYPE$1: - // debugFn('call ARRAY_TYPE') - return !checkIsArray(value.arg) - // @TODO when the type is not present, it always fall through here - // so we need to find a way to actually pre-check the type first - // AKA check the contract.json map before running here - case (tmp = isArrayLike$1(type)) !== false: - // debugFn('call ARRAY_LIKE: %O', value) - return !arrayTypeHandler(value, tmp) - default: - return !combineFn(type)(value.arg) - } -}; - -/** - * it get too longer to fit in one line so break it out from the fn below - * @param {*} arg value - * @param {object} param config - * @return {*} value or apply default value - */ -var getOptionalValue = function(arg, param) { - if (!isUndefined(arg)) { - return arg; - } - return (param.optional === true && !isUndefined(param.defaultvalue) ? param.defaultvalue : null) -}; - -/** - * padding the arguments with defaultValue if the arguments did not provide the value - * this will be the name export - * @param {array} args normalized arguments - * @param {array} params from contract.json - * @return {array} merge the two together - */ -var normalizeArgs = function(args, params) { - // first we should check if this call require a validation at all - // there will be situation where the function doesn't need args and params - if (!checkIsArray(params)) { - // debugFn('params value', params) - throw new JsonqlError(PARAMS_NOT_ARRAY_ERR) - } - if (params.length === 0) { - return []; - } - if (!checkIsArray(args)) { - throw new JsonqlError(ARGS_NOT_ARRAY_ERR) - } - // debugFn(args, params); - // fall through switch - switch(true) { - case args.length == params.length: // standard - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] - } - ); }); - case params[0].variable === true: // using spread syntax - var type = params[0].type; - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, // keep the index for reference - param: params[i] || { type: type, name: '_' } - } - ); }); - // with optional defaultValue parameters - case args.length < params.length: - return params.map(function (param, i) { return ( - { - param: param, - index: i, - arg: getOptionalValue(args[i], param), - optional: param.optional || false - } - ); }); - // this one pass more than it should have anything after the args.length will be cast as any type - case args.length > params.length && params.length === 1: - // this happens when we have those array. type - var tmp, _type = [ DEFAULT_TYPE$1 ]; - // we only looking at the first one, this might be a @BUG! - if ((tmp = isArrayLike$1(params[0].type[0])) !== false) { - _type = tmp; - } - // if not then we fall back to the following - return args.map(function (arg, i) { return ( - { - arg: arg, - index: i, - param: params[i] || { type: _type, name: '_' } - } - ); }); - // @TODO find out if there is more cases not cover - default: // this should never happen - // debugFn('args', args) - // debugFn('params', params) - // this is unknown therefore we just throw it! - throw new JsonqlError(EXCEPTION_CASE_ERR, { args: args, params: params }) - } -}; - -// what we want is after the validaton we also get the normalized result -// which is with the optional property if the argument didn't provide it -/** - * process the array of params back to their arguments - * @param {array} result the params result - * @return {array} arguments - */ -var processReturn = function (result) { return result.map(function (r) { return r.arg; }); }; - -/** - * validator main interface - * @param {array} args the arguments pass to the method call - * @param {array} params from the contract for that method - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {array} empty array on success, or failed parameter and reasons - */ -var validateSync = function(args, params, withResult) { - var obj; - - if ( withResult === void 0 ) withResult = false; - var cleanArgs = normalizeArgs(args, params); - var checkResult = cleanArgs.filter(function (p) { - if (p.param.optional === true) { - return optionalHandler(p) - } - // because array of types means OR so if one pass means pass - return !(p.param.type.length > p.param.type.filter( - function (type) { return validateHandler(type, p); } - ).length) - }); - // using the same convention we been using all this time - return !withResult ? checkResult : ( obj = {}, obj[ERROR_KEY] = checkResult, obj[DATA_KEY] = processReturn(cleanArgs), obj ) -}; - -/** - * A wrapper method that return promise - * @param {array} args arguments - * @param {array} params from contract.json - * @param {boolean} [withResul=false] if true then this will return the normalize result as well - * @return {object} promise.then or catch - */ -var validateAsync = function(args, params, withResult) { - if ( withResult === void 0 ) withResult = false; - - return new Promise(function (resolver, rejecter) { - var result = validateSync(args, params, withResult); - if (withResult) { - return result[ERROR_KEY].length ? rejecter(result[ERROR_KEY]) - : resolver(result[DATA_KEY]) - } - // the different is just in the then or catch phrase - return result.length ? rejecter(result) : resolver([]) - }) -}; - -/** - * @param {array} arr Array for check - * @param {*} value target - * @return {boolean} true on successs - */ -var isInArray = function(arr, value) { - return !!arr.filter(function (a) { return a === value; }).length; -}; - -/** - * @param {object} obj for search - * @param {string} key target - * @return {boolean} true on success - */ -var checkKeyInObject = function(obj, key) { - var keys = Object.keys(obj); - return isInArray(keys, key) -}; - -// import debug from 'debug'; -// const debugFn = debug('jsonql-params-validator:options:prepare') - -// just not to make my head hurt -var isEmpty = function (value) { return !notEmpty(value); }; - -/** - * Map the alias to their key then grab their value over - * @param {object} config the user supplied config - * @param {object} appProps the default option map - * @return {object} the config keys replaced with the appProps key by the ALIAS - */ -function mapAliasConfigKeys(config, appProps) { - // need to do two steps - // 1. take key with alias key - var aliasMap = omitBy(appProps, function (value, k) { return !value[ALIAS_KEY$1]; } ); - if (isEqual(aliasMap, {})) { - return config; - } - return mapKeys(config, function (v, key) { return findKey(aliasMap, function (o) { return o.alias === key; }) || key; }) -} - -/** - * We only want to run the valdiation against the config (user supplied) value - * but keep the defaultOptions untouch - * @param {object} config configuraton supplied by user - * @param {object} appProps the default options map - * @return {object} the pristine values that will add back to the final output - */ -function preservePristineValues(config, appProps) { - // @BUG this will filter out those that is alias key - // we need to first map the alias keys back to their full key - var _config = mapAliasConfigKeys(config, appProps); - // take the default value out - var pristineValues = mapValues( - omitBy(appProps, function (value, key) { return checkKeyInObject(_config, key); }), - function (value) { return value.args; } - ); - // for testing the value - var checkAgainstAppProps = omitBy(appProps, function (value, key) { return !checkKeyInObject(_config, key); }); - // output - return { - pristineValues: pristineValues, - checkAgainstAppProps: checkAgainstAppProps, - config: _config // passing this correct values back - } -} - -/** - * This will take the value that is ONLY need to check - * @param {object} config that one - * @param {object} props map for creating checking - * @return {object} put that arg into the args - */ -function processConfigAction(config, props) { - // debugFn('processConfigAction', props) - // v.1.2.0 add checking if its mark optional and the value is empty then pass - return mapValues(props, function (value, key) { - var obj, obj$1; - - return ( - isUndefined(config[key]) || (value[OPTIONAL_KEY$1] === true && isEmpty(config[key])) - ? merge({}, value, ( obj = {}, obj[KEY_WORD$1] = true, obj )) - : ( obj$1 = {}, obj$1[ARGS_KEY$1] = config[key], obj$1[TYPE_KEY$1] = value[TYPE_KEY$1], obj$1[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1] || false, obj$1[ENUM_KEY$1] = value[ENUM_KEY$1] || false, obj$1[CHECKER_KEY$1] = value[CHECKER_KEY$1] || false, obj$1 ) - ); - } - ) -} - -/** - * Quick transform - * @TODO we should only validate those that is pass from the config - * and pass through those values that is from the defaultOptions - * @param {object} opts that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ -function prepareArgsForValidation(opts, appProps) { - var ref = preservePristineValues(opts, appProps); - var config = ref.config; - var pristineValues = ref.pristineValues; - var checkAgainstAppProps = ref.checkAgainstAppProps; - // output - return [ - processConfigAction(config, checkAgainstAppProps), - pristineValues - ] -} - -// breaking the whole thing up to see what cause the multiple calls issue - -// import debug from 'debug'; -// const debugFn = debug('jsonql-params-validator:options:validation') - -/** - * just make sure it returns an array to use - * @param {*} arg input - * @return {array} output - */ -var toArray = function (arg) { return checkIsArray(arg) ? arg : [arg]; }; - -/** - * DIY in array - * @param {array} arr to check against - * @param {*} value to check - * @return {boolean} true on OK - */ -var inArray = function (arr, value) { return ( - !!arr.filter(function (v) { return v === value; }).length -); }; - -/** - * break out to make the code easier to read - * @param {object} value to process - * @param {function} cb the validateSync - * @return {array} empty on success - */ -function validateHandler$1(value, cb) { - var obj; - - // cb is the validateSync methods - var args = [ - [ value[ARGS_KEY$1] ], - [( obj = {}, obj[TYPE_KEY$1] = toArray(value[TYPE_KEY$1]), obj[OPTIONAL_KEY$1] = value[OPTIONAL_KEY$1], obj )] - ]; - // debugFn('validateHandler', args) - return Reflect.apply(cb, null, args) -} - -/** - * Check against the enum value if it's provided - * @param {*} value to check - * @param {*} enumv to check against if it's not false - * @return {boolean} true on OK - */ -var enumHandler = function (value, enumv) { - if (checkIsArray(enumv)) { - return inArray(enumv, value) - } - return true; -}; - -/** - * Allow passing a function to check the value - * There might be a problem here if the function is incorrect - * and that will makes it hard to debug what is going on inside - * @TODO there could be a few feature add to this one under different circumstance - * @param {*} value to check - * @param {function} checker for checking - */ -var checkerHandler = function (value, checker) { - try { - return isFunction(checker) ? checker.apply(null, [value]) : false; - } catch (e) { - return false; - } -}; - -/** - * Taken out from the runValidaton this only validate the required values - * @param {array} args from the config2argsAction - * @param {function} cb validateSync - * @return {array} of configuration values - */ -function runValidationAction(cb) { - return function (value, key) { - // debugFn('runValidationAction', key, value) - if (value[KEY_WORD$1]) { - return value[ARGS_KEY$1] - } - var check = validateHandler$1(value, cb); - if (check.length) { - // debugFn('runValidationAction', key, value) - throw new JsonqlTypeError(key, check) - } - if (value[ENUM_KEY$1] !== false && !enumHandler(value[ARGS_KEY$1], value[ENUM_KEY$1])) { - throw new JsonqlEnumError(key) - } - if (value[CHECKER_KEY$1] !== false && !checkerHandler(value[ARGS_KEY$1], value[CHECKER_KEY$1])) { - throw new JsonqlCheckerError(key) - } - return value[ARGS_KEY$1] - } -} - -/** - * @param {object} args from the config2argsAction - * @param {function} cb validateSync - * @return {object} of configuration values - */ -function runValidation(args, cb) { - var argsForValidate = args[0]; - var pristineValues = args[1]; - // turn the thing into an array and see what happen here - // debugFn('_args', argsForValidate) - var result = mapValues(argsForValidate, runValidationAction(cb)); - return merge(result, pristineValues) -} - -// this is port back from the client to share across all projects - -// import debug from 'debug' -// const debugFn = debug('jsonql-params-validator:check-options-async') - -/** - * Quick transform - * @param {object} config that one - * @param {object} appProps mutation configuration options - * @return {object} put that arg into the args - */ -var configToArgs = function (config, appProps) { - return Promise.resolve( - prepareArgsForValidation(config, appProps) - ) -}; - -/** - * @param {object} config user provide configuration option - * @param {object} appProps mutation configuration options - * @param {object} constProps the immutable configuration options - * @param {function} cb the validateSync method - * @return {object} Promise resolve merge config object - */ -function checkOptionsAsync(config, appProps, constProps, cb) { - if ( config === void 0 ) config = {}; - - return configToArgs(config, appProps) - .then(function (args1) { - // debugFn('args', args1) - return runValidation(args1, cb) - }) - // next if every thing good then pass to final merging - .then(function (args2) { return merge({}, args2, constProps); }) -} - -// create function to construct the config entry so we don't need to keep building object -// import debug from 'debug'; -// const debugFn = debug('jsonql-params-validator:construct-config'); -/** - * @param {*} args value - * @param {string} type for value - * @param {boolean} [optional=false] - * @param {boolean|array} [enumv=false] - * @param {boolean|function} [checker=false] - * @return {object} config entry - */ -function constructConfigFn(args, type, optional, enumv, checker, alias) { - if ( optional === void 0 ) optional=false; - if ( enumv === void 0 ) enumv=false; - if ( checker === void 0 ) checker=false; - if ( alias === void 0 ) alias=false; - - var base = {}; - base[ARGS_KEY] = args; - base[TYPE_KEY] = type; - if (optional === true) { - base[OPTIONAL_KEY] = true; - } - if (checkIsArray(enumv)) { - base[ENUM_KEY] = enumv; - } - if (isFunction(checker)) { - base[CHECKER_KEY] = checker; - } - if (isString(alias)) { - base[ALIAS_KEY] = alias; - } - return base; -} - -// export also create wrapper methods - -// import debug from 'debug'; -// const debugFn = debug('jsonql-params-validator:options:index'); - -/** - * This has a different interface - * @param {*} value to supply - * @param {string|array} type for checking - * @param {object} params to map against the config check - * @param {array} params.enumv NOT enum - * @param {boolean} params.optional false then nothing - * @param {function} params.checker need more work on this one later - * @param {string} params.alias mostly for cmd - */ -var createConfig = function (value, type, params) { - if ( params === void 0 ) params = {}; - - // Note the enumv not ENUM - // const { enumv, optional, checker, alias } = params; - // let args = [value, type, optional, enumv, checker, alias]; - var o = params[OPTIONAL_KEY]; - var e = params[ENUM_KEY]; - var c = params[CHECKER_KEY]; - var a = params[ALIAS_KEY]; - return constructConfigFn.apply(null, [value, type, o, e, c, a]) -}; - -/** - * We recreate the method here to avoid the circlar import - * @param {object} config user supply configuration - * @param {object} appProps mutation options - * @param {object} [constantProps={}] optional: immutation options - * @return {object} all checked configuration - */ -var checkConfigAsync = function(validateSync) { - return function(config, appProps, constantProps) { - if ( constantProps === void 0 ) constantProps= {}; - - return checkOptionsAsync(config, appProps, constantProps, validateSync) - } -}; - -// since this need to use everywhere might as well include in the validator - -function checkIsContract(contract) { - return checkIsObject(contract) - && ( - checkKeyInObject(contract, QUERY_NAME) - || checkKeyInObject(contract, MUTATION_NAME) - || checkKeyInObject(contract, SOCKET_NAME) - ) -} - -// craete several helper function to construct / extract the payload - -/** - * Get name from the payload (ported back from jsonql-koa) - * @param {*} payload to extract from - * @return {string} name - */ -function getNameFromPayload(payload) { - return Object.keys(payload)[0] -} - -/** - * @param {string} resolverName name of function - * @param {array} [args=[]] from the ...args - * @param {boolean} [jsonp = false] add v1.3.0 to koa - * @return {object} formatted argument - */ -function createQuery(resolverName, args, jsonp) { - var obj; - - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - if (checkIsString(resolverName) && checkIsArray(args)) { - var payload = {}; - payload[QUERY_ARG_NAME] = args; - if (jsonp === true) { - return payload; - } - return ( obj = {}, obj[resolverName] = payload, obj ) - } - throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!", { resolverName: resolverName, args: args }) -} - -// string version of the above -function createQueryStr(resolverName, args, jsonp) { - if ( args === void 0 ) args = []; - if ( jsonp === void 0 ) jsonp = false; - - return JSON.stringify(createQuery(resolverName, args, jsonp)) -} - -// export -var isString$1 = checkIsString; -var isArray$1 = checkIsArray; -var validateSync$1 = validateSync; -var validateAsync$1 = validateAsync; - -var createConfig$1 = createConfig; - -var checkConfigAsync$1 = checkConfigAsync(validateSync); - -var isKeyInObject = checkKeyInObject; - -var isContract = checkIsContract; -var createQueryStr$1 = createQueryStr; -var getNameFromPayload$1 = getNameFromPayload; - -/** - * Try to normalize it to use between browser and node - * @param {string} name for the debug output - * @return {function} debug - */ -var getDebug = function (name) { - if (debug$2) { - return debug$2('jsonql-ws-client').extend(name) - } - return function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - console.info.apply(null, [name].concat(args)); - } -}; -try { - if (window && window.localStorage) { - localStorage.setItem('DEBUG', 'jsonql-ws-client*'); - } -} catch(e) {} - -// since both the ws and io version are -var debugFn = getDebug('create-nsp-client'); -/** - * wrapper method to create a nsp without login - * @param {string|boolean} namespace namespace url could be false - * @param {object} opts configuration - * @return {object} ws client instance - */ -var nspClient = function (namespace, opts) { - var wssPath = opts.wssPath; - var wsOptions = opts.wsOptions; - var hostname = opts.hostname; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - return opts.nspClient(url, wsOptions) -}; - -/** - * wrapper method to create a nsp with token auth - * @param {string} namespace namespace url - * @param {object} opts configuration - * @return {object} ws client instance - */ -var nspAuthClient = function (namespace, opts) { - var wssPath = opts.wssPath; - var token = opts.token; - var wsOptions = opts.wsOptions; - var hostname = opts.hostname; - var url = namespace ? [hostname, namespace].join('/') : wssPath; - return opts.nspAuthClient(url, token, wsOptions) -}; - -// constants - -var SOCKET_IO = JS_WS_SOCKET_IO_NAME; -var WS = JS_WS_NAME; - -var AVAILABLE_SERVERS = [SOCKET_IO, WS]; - -var SOCKET_NOT_DEFINE_ERR = 'socket is not define in the contract file!'; - -var MISSING_PROP_ERR = 'Missing property in contract!'; - -var EMIT_EVT = EMIT_REPLY_TYPE; - -var UNKNOWN_RESULT = 'UKNNOWN RESULT!'; - -var MY_NAMESPACE = 'myNamespace'; - -/** - * Got to make sure the connection order otherwise - * it will hang - * @param {object} nspSet contract - * @param {string} publicNamespace like the name said - * @return {array} namespaces in order - */ -function getNamespaceInOrder(nspSet, publicNamespace) { - var names = []; // need to make sure the order! - for (var namespace in nspSet) { - if (namespace === publicNamespace) { - names[1] = namespace; - } else { - names[0] = namespace; - } - } - return names; -} - -var obj, obj$1; -var debug = getDebug('check-options'); - -var fixWss = function (url, serverType) { - // ws only allow ws:// path - if (serverType===WS) { - return url.replace('http://', 'ws://') - } - return url; -}; - -var getHostName = function () { return ( - [window.location.protocol, window.location.host].join('//') -); }; - -var constProps = { - // this will be the switcher! - nspClient: null, - nspAuthClient: null, - // contructed path - wssPath: '' -}; - -var defaultOptions = { - loginHandlerName: createConfig$1(ISSUER_NAME, [STRING_TYPE]), - logoutHandlerName: createConfig$1(LOGOUT_NAME, [STRING_TYPE]), - // we will use this for determine the socket.io client type as well - useJwt: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE]), - hostname: createConfig$1(false, [STRING_TYPE]), - namespace: createConfig$1(JSONQL_PATH, [STRING_TYPE]), - wsOptions: createConfig$1({transports: ['websocket'], 'force new connection' : true}, [OBJECT_TYPE]), - serverType: createConfig$1(SOCKET_IO, [STRING_TYPE], ( obj = {}, obj[ENUM_KEY] = AVAILABLE_SERVERS, obj )), - // we require the contract already generated and pass here - contract: createConfig$1({}, [OBJECT_TYPE], ( obj$1 = {}, obj$1[CHECKER_KEY] = isContract, obj$1 )), - enableAuth: createConfig$1(false, [BOOLEAN_TYPE]), - token: createConfig$1(false, [STRING_TYPE]) -}; -// export -function checkOptions(config) { - return checkConfigAsync$1(config, defaultOptions, constProps) - .then(function (opts) { - if (!opts.hostname) { - opts.hostname = getHostName(); - } - // @TODO the contract now will supply the namespace information - // and we need to use that to group the namespace call - opts.wssPath = fixWss([opts.hostname, opts.namespace].join('/'), opts.serverType); - - debug('opts', opts); - return opts; - }) -} - -var NB_EVENT_SERVICE_PRIVATE_STORE = new WeakMap(); -var NB_EVENT_SERVICE_PRIVATE_LAZY = new WeakMap(); - -/** - * generate a 32bit hash based on the function.toString() - * _from http://stackoverflow.com/questions/7616461/generate-a-hash-_from-string-in-javascript-jquery - * @param {string} s the converted to string function - * @return {string} the hashed function string - */ -function hashCode(s) { - return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0) -} - -// making all the functionality on it's own -// import { WatchClass } from './watch' - -var SuspendClass = function SuspendClass() { - // suspend, release and queue - this.__suspend__ = null; - this.queueStore = new Set(); - /* - this.watch('suspend', function(value, prop, oldValue) { - this.logger(`${prop} set from ${oldValue} to ${value}`) - // it means it set the suspend = true then release it - if (oldValue === true && value === false) { - // we want this happen after the return happens - setTimeout(() => { - this.release() - }, 1) - } - return value; // we need to return the value to store it - }) - */ -}; - -var prototypeAccessors = { $suspend: { configurable: true },$queues: { configurable: true } }; - -/** - * setter to set the suspend and check if it's boolean value - * @param {boolean} value to trigger - */ -prototypeAccessors.$suspend.set = function (value) { - var this$1 = this; - - if (typeof value === 'boolean') { - var lastValue = this.__suspend__; - this.__suspend__ = value; - this.logger('($suspend)', ("Change from " + lastValue + " --> " + value)); - if (lastValue === true && value === false) { - setTimeout(function () { - this$1.release(); - }, 1); - } - } else { - throw new Error("$suspend only accept Boolean value!") - } -}; - -/** - * queuing call up when it's in suspend mode - * @param {any} value - * @return {Boolean} true when added or false when it's not - */ -SuspendClass.prototype.$queue = function $queue () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - if (this.__suspend__ === true) { - this.logger('($queue)', 'added to $queue', args); - // there shouldn't be any duplicate ... - this.queueStore.add(args); - } - return this.__suspend__; -}; - -/** - * a getter to get all the store queue - * @return {array} Set turn into Array before return - */ -prototypeAccessors.$queues.get = function () { - var size = this.queueStore.size; - this.logger('($queues)', ("size: " + size)); - if (size > 0) { - return Array.from(this.queueStore) - } - return [] -}; - -/** - * Release the queue - * @return {int} size if any - */ -SuspendClass.prototype.release = function release () { - var this$1 = this; - - var size = this.queueStore.size; - this.logger('(release)', ("Release was called " + size)); - if (size > 0) { - var queue = Array.from(this.queueStore); - this.queueStore.clear(); - this.logger('queue', queue); - queue.forEach(function (args) { - this$1.logger(args); - Reflect.apply(this$1.$trigger, this$1, args); - }); - this.logger(("Release size " + (this.queueStore.size))); - } -}; - -Object.defineProperties( SuspendClass.prototype, prototypeAccessors ); - -// break up the main file because its getting way too long - -var NbEventServiceBase = /*@__PURE__*/(function (SuspendClass) { - function NbEventServiceBase(config) { - if ( config === void 0 ) config = {}; - - SuspendClass.call(this); - if (config.logger && typeof config.logger === 'function') { - this.logger = config.logger; - } - this.keep = config.keep; - // for the $done setter - this.result = config.keep ? [] : null; - // we need to init the store first otherwise it could be a lot of checking later - this.normalStore = new Map(); - this.lazyStore = new Map(); - } - - if ( SuspendClass ) NbEventServiceBase.__proto__ = SuspendClass; - NbEventServiceBase.prototype = Object.create( SuspendClass && SuspendClass.prototype ); - NbEventServiceBase.prototype.constructor = NbEventServiceBase; - - var prototypeAccessors = { normalStore: { configurable: true },lazyStore: { configurable: true } }; - - /** - * validate the event name(s) - * @param {string[]} evt event name - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validateEvt = function validateEvt () { - var this$1 = this; - var evt = [], len = arguments.length; - while ( len-- ) evt[ len ] = arguments[ len ]; - - evt.forEach(function (e) { - if (typeof e !== 'string') { - this$1.logger('(validateEvt)', e); - throw new Error("event name must be string type!") - } - }); - return true; - }; - - /** - * Simple quick check on the two main parameters - * @param {string} evt event name - * @param {function} callback function to call - * @return {boolean} true when OK - */ - NbEventServiceBase.prototype.validate = function validate (evt, callback) { - if (this.validateEvt(evt)) { - if (typeof callback === 'function') { - return true; - } - } - throw new Error("callback required to be function type!") - }; - - /** - * Check if this type is correct or not added in V1.5.0 - * @param {string} type for checking - * @return {boolean} true on OK - */ - NbEventServiceBase.prototype.validateType = function validateType (type) { - var types = ['on', 'only', 'once', 'onlyOnce']; - return !!types.filter(function (t) { return type === t; }).length; - }; - - /** - * Run the callback - * @param {function} callback function to execute - * @param {array} payload for callback - * @param {object} ctx context or null - * @return {void} the result store in $done - */ - NbEventServiceBase.prototype.run = function run (callback, payload, ctx) { - this.logger('(run)', callback, payload, ctx); - this.$done = Reflect.apply(callback, ctx, this.toArray(payload)); - }; - - /** - * Take the content out and remove it from store id by the name - * @param {string} evt event name - * @param {string} [storeName = lazyStore] name of store - * @return {object|boolean} content or false on not found - */ - NbEventServiceBase.prototype.takeFromStore = function takeFromStore (evt, storeName) { - if ( storeName === void 0 ) storeName = 'lazyStore'; - - var store = this[storeName]; // it could be empty at this point - if (store) { - this.logger('(takeFromStore)', storeName, store); - if (store.has(evt)) { - var content = store.get(evt); - this.logger('(takeFromStore)', ("has " + evt), content); - store.delete(evt); - return content; - } - return false; - } - throw new Error((storeName + " is not supported!")) - }; - - /** - * The add to store step is similar so make it generic for resuse - * @param {object} store which store to use - * @param {string} evt event name - * @param {spread} args because the lazy store and normal store store different things - * @return {array} store and the size of the store - */ - NbEventServiceBase.prototype.addToStore = function addToStore (store, evt) { - var args = [], len = arguments.length - 2; - while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; - - var fnSet; - if (store.has(evt)) { - this.logger('(addToStore)', (evt + " existed")); - fnSet = store.get(evt); - } else { - this.logger('(addToStore)', ("create new Set for " + evt)); - // this is new - fnSet = new Set(); - } - // lazy only store 2 items - this is not the case in V1.6.0 anymore - // we need to check the first parameter is string or not - if (args.length > 2) { - if (Array.isArray(args[0])) { // lazy store - // check if this type of this event already register in the lazy store - var t = args[2]; - if (!this.checkTypeInLazyStore(evt, t)) { - fnSet.add(args); - } - } else { - if (!this.checkContentExist(args, fnSet)) { - this.logger('(addToStore)', "insert new", args); - fnSet.add(args); - } - } - } else { // add straight to lazy store - fnSet.add(args); - } - store.set(evt, fnSet); - return [store, fnSet.size] - }; - - /** - * @param {array} args for compare - * @param {object} fnSet A Set to search from - * @return {boolean} true on exist - */ - NbEventServiceBase.prototype.checkContentExist = function checkContentExist (args, fnSet) { - var list = Array.from(fnSet); - return !!list.filter(function (l) { - var hash = l[0]; - if (hash === args[0]) { - return true; - } - return false; - }).length; - }; - - /** - * get the existing type to make sure no mix type add to the same store - * @param {string} evtName event name - * @param {string} type the type to check - * @return {boolean} true you can add, false then you can't add this type - */ - NbEventServiceBase.prototype.checkTypeInStore = function checkTypeInStore (evtName, type) { - this.validateEvt(evtName, type); - var all = this.$get(evtName, true); - if (all === false) { - // pristine it means you can add - return true; - } - // it should only have ONE type in ONE event store - return !all.filter(function (list) { - var t = list[3]; - return type !== t; - }).length; - }; - - /** - * This is checking just the lazy store because the structure is different - * therefore we need to use a new method to check it - */ - NbEventServiceBase.prototype.checkTypeInLazyStore = function checkTypeInLazyStore (evtName, type) { - this.validateEvt(evtName, type); - var store = this.lazyStore.get(evtName); - this.logger('(checkTypeInLazyStore)', store); - if (store) { - return !!Array - .from(store) - .filter(function (l) { - var t = l[2]; - return t !== type; - }).length - } - return false; - }; - - /** - * wrapper to re-use the addToStore, - * V1.3.0 add extra check to see if this type can add to this evt - * @param {string} evt event name - * @param {string} type on or once - * @param {function} callback function - * @param {object} context the context the function execute in or null - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToNormalStore = function addToNormalStore (evt, type, callback, context) { - if ( context === void 0 ) context = null; - - this.logger('(addToNormalStore)', evt, type, 'try to add to normal store'); - // @TODO we need to check the existing store for the type first! - if (this.checkTypeInStore(evt, type)) { - this.logger('(addToNormalStore)', (type + " can add to " + evt + " normal store")); - var key = this.hashFnToKey(callback); - var args = [this.normalStore, evt, key, callback, context, type]; - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.normalStore = _store; - return size; - } - return false; - }; - - /** - * Add to lazy store this get calls when the callback is not register yet - * so we only get a payload object or even nothing - * @param {string} evt event name - * @param {array} payload of arguments or empty if there is none - * @param {object} [context=null] the context the callback execute in - * @param {string} [type=false] register a type so no other type can add to this evt - * @return {number} size of the store - */ - NbEventServiceBase.prototype.addToLazyStore = function addToLazyStore (evt, payload, context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - // this is add in V1.6.0 - // when there is type then we will need to check if this already added in lazy store - // and no other type can add to this lazy store - var args = [this.lazyStore, evt, this.toArray(payload), context]; - if (type) { - args.push(type); - } - var ref = Reflect.apply(this.addToStore, this, args); - var _store = ref[0]; - var size = ref[1]; - this.lazyStore = _store; - return size; - }; - - /** - * make sure we store the argument correctly - * @param {*} arg could be array - * @return {array} make sured - */ - NbEventServiceBase.prototype.toArray = function toArray (arg) { - return Array.isArray(arg) ? arg : [arg]; - }; - - /** - * setter to store the Set in private - * @param {object} obj a Set - */ - prototypeAccessors.normalStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_STORE.set(this, obj); - }; - - /** - * @return {object} Set object - */ - prototypeAccessors.normalStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_STORE.get(this) - }; - - /** - * setter to store the Set in lazy store - * @param {object} obj a Set - */ - prototypeAccessors.lazyStore.set = function (obj) { - NB_EVENT_SERVICE_PRIVATE_LAZY.set(this , obj); - }; - - /** - * @return {object} the lazy store Set - */ - prototypeAccessors.lazyStore.get = function () { - return NB_EVENT_SERVICE_PRIVATE_LAZY.get(this) - }; - - /** - * generate a hashKey to identify the function call - * The build-in store some how could store the same values! - * @param {function} fn the converted to string function - * @return {string} hashKey - */ - NbEventServiceBase.prototype.hashFnToKey = function hashFnToKey (fn) { - return hashCode(fn.toString()) + ''; - }; - - Object.defineProperties( NbEventServiceBase.prototype, prototypeAccessors ); - - return NbEventServiceBase; -}(SuspendClass)); - -// The top level -// export -var EventService = /*@__PURE__*/(function (NbStoreService) { - function EventService(config) { - if ( config === void 0 ) config = {}; - - NbStoreService.call(this, config); - } - - if ( NbStoreService ) EventService.__proto__ = NbStoreService; - EventService.prototype = Object.create( NbStoreService && NbStoreService.prototype ); - EventService.prototype.constructor = EventService; - - var prototypeAccessors = { $done: { configurable: true } }; - - /** - * logger function for overwrite - */ - EventService.prototype.logger = function logger () {}; - - ////////////////////////// - // PUBLIC METHODS // - ////////////////////////// - - /** - * Register your evt handler, note we don't check the type here, - * we expect you to be sensible and know what you are doing. - * @param {string} evt name of event - * @param {function} callback bind method --> if it's array or not - * @param {object} [context=null] to execute this call in - * @return {number} the size of the store - */ - EventService.prototype.$on = function $on (evt , callback , context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - var type = 'on'; - this.validate(evt, callback); - // first need to check if this evt is in lazy store - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register first then call later - if (lazyStoreContent === false) { - this.logger('($on)', (evt + " callback is not in lazy store")); - // @TODO we need to check if there was other listener to this - // event and are they the same type then we could solve that - // register the different type to the same event name - - return this.addToNormalStore(evt, type, callback, context) - } - this.logger('($on)', (evt + " found in lazy store")); - // this is when they call $trigger before register this callback - var size = 0; - lazyStoreContent.forEach(function (content) { - var payload = content[0]; - var ctx = content[1]; - var t = content[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.run(callback, payload, context || ctx); - size += this$1.addToNormalStore(evt, type, callback, context || ctx); - }); - return size; - }; - - /** - * once only registered it once, there is no overwrite option here - * @NOTE change in v1.3.0 $once can add multiple listeners - * but once the event fired, it will remove this event (see $only) - * @param {string} evt name - * @param {function} callback to execute - * @param {object} [context=null] the handler execute in - * @return {boolean} result - */ - EventService.prototype.$once = function $once (evt , callback , context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'once'; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (lazyStoreContent === false) { - this.logger('($once)', (evt + " not in the lazy store")); - // v1.3.0 $once now allow to add multiple listeners - return this.addToNormalStore(evt, type, callback, context) - } else { - // now this is the tricky bit - // there is a potential bug here that cause by the developer - // if they call $trigger first, the lazy won't know it's a once call - // so if in the middle they register any call with the same evt name - // then this $once call will be fucked - add this to the documentation - this.logger('($once)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - }; - - /** - * This one event can only bind one callbackback - * @param {string} evt event name - * @param {function} callback event handler - * @param {object} [context=null] the context the event handler execute in - * @return {boolean} true bind for first time, false already existed - */ - EventService.prototype.$only = function $only (evt, callback, context) { - var this$1 = this; - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'only'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($only)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($only)', (evt + " found data in lazy store to execute")); - var list = Array.from(lazyStoreContent); - // $only allow to trigger this multiple time on the single handler - list.forEach( function (l) { - var payload = l[0]; - var ctx = l[1]; - var t = l[2]; - if (t && t !== type) { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this$1.run(callback, payload, context || ctx); - }); - } - return added; - }; - - /** - * $only + $once this is because I found a very subtile bug when we pass a - * resolver, rejecter - and it never fire because that's OLD adeed in v1.4.0 - * @param {string} evt event name - * @param {function} callback to call later - * @param {object} [context=null] exeucte context - * @return {void} - */ - EventService.prototype.$onlyOnce = function $onlyOnce (evt, callback, context) { - if ( context === void 0 ) context = null; - - this.validate(evt, callback); - var type = 'onlyOnce'; - var added = false; - var lazyStoreContent = this.takeFromStore(evt); - // this is normal register before call $trigger - var nStore = this.normalStore; - if (!nStore.has(evt)) { - this.logger("($onlyOnce)", (evt + " add to store")); - added = this.addToNormalStore(evt, type, callback, context); - } - if (lazyStoreContent !== false) { - // there are data store in lazy store - this.logger('($onlyOnce)', lazyStoreContent); - var list = Array.from(lazyStoreContent); - // should never have more than 1 - var ref = list[0]; - var payload = ref[0]; - var ctx = ref[1]; - var t = ref[2]; - if (t && t !== 'onlyOnce') { - throw new Error(("You are trying to register an event already been taken by other type: " + t)) - } - this.run(callback, payload, context || ctx); - // remove this evt from store - this.$off(evt); - } - return added; - }; - - /** - * This is a shorthand of $off + $on added in V1.5.0 - * @param {string} evt event name - * @param {function} callback to exeucte - * @param {object} [context = null] or pass a string as type - * @param {string} [type=on] what type of method to replace - * @return {} - */ - EventService.prototype.$replace = function $replace (evt, callback, context, type) { - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = 'on'; - - if (this.validateType(type)) { - this.$off(evt); - var method = this['$' + type]; - return Reflect.apply(method, this, [evt, callback, context]) - } - throw new Error((type + " is not supported!")) - }; - - /** - * trigger the event - * @param {string} evt name NOT allow array anymore! - * @param {mixed} [payload = []] pass to fn - * @param {object|string} [context = null] overwrite what stored - * @param {string} [type=false] if pass this then we need to add type to store too - * @return {number} if it has been execute how many times - */ - EventService.prototype.$trigger = function $trigger (evt , payload , context, type) { - if ( payload === void 0 ) payload = []; - if ( context === void 0 ) context = null; - if ( type === void 0 ) type = false; - - this.validateEvt(evt); - var found = 0; - // first check the normal store - var nStore = this.normalStore; - this.logger('($trigger)', 'normalStore', nStore); - if (nStore.has(evt)) { - // @1.8.0 to add the suspend queue - var added = this.$queue(evt, payload, context, type); - this.logger('($trigger)', evt, 'found; add to queue: ', added); - if (added === true) { - return false; // not executed - } - var nSet = Array.from(nStore.get(evt)); - var ctn = nSet.length; - var hasOnce = false; - for (var i=0; i < ctn; ++i) { - ++found; - // this.logger('found', found) - var ref = nSet[i]; - var _ = ref[0]; - var callback = ref[1]; - var ctx = ref[2]; - var type$1 = ref[3]; - this.run(callback, payload, context || ctx); - if (type$1 === 'once' || type$1 === 'onlyOnce') { - hasOnce = true; - } - } - if (hasOnce) { - nStore.delete(evt); - } - return found; - } - // now this is not register yet - this.addToLazyStore(evt, payload, context, type); - return found; - }; - - /** - * this is an alias to the $trigger - * @NOTE breaking change in V1.6.0 we swap the parameter around - * @param {string} evt event name - * @param {*} params pass to the callback - * @param {string} type of call - * @param {object} context what context callback execute in - * @return {*} from $trigger - */ - EventService.prototype.$call = function $call (evt, params, type, context) { - if ( type === void 0 ) type = false; - if ( context === void 0 ) context = null; - - var args = [evt, params]; - args.push(context, type); - return Reflect.apply(this.$trigger, this, args) - }; - - /** - * remove the evt from all the stores - * @param {string} evt name - * @return {boolean} true actually delete something - */ - EventService.prototype.$off = function $off (evt) { - this.validateEvt(evt); - var stores = [ this.lazyStore, this.normalStore ]; - var found = false; - stores.forEach(function (store) { - if (store.has(evt)) { - found = true; - store.delete(evt); - } - }); - return found; - }; - - /** - * return all the listener from the event - * @param {string} evtName event name - * @param {boolean} [full=false] if true then return the entire content - * @return {array|boolean} listerner(s) or false when not found - */ - EventService.prototype.$get = function $get (evt, full) { - if ( full === void 0 ) full = false; - - this.validateEvt(evt); - var store = this.normalStore; - if (store.has(evt)) { - return Array - .from(store.get(evt)) - .map( function (l) { - if (full) { - return l; - } - var key = l[0]; - var callback = l[1]; - return callback; - }) - } - return false; - }; - - /** - * store the return result from the run - * @param {*} value whatever return from callback - */ - prototypeAccessors.$done.set = function (value) { - this.logger('($done)', 'value: ', value); - if (this.keep) { - this.result.push(value); - } else { - this.result = value; - } - }; - - /** - * @TODO is there any real use with the keep prop? - * getter for $done - * @return {*} whatever last store result - */ - prototypeAccessors.$done.get = function () { - if (this.keep) { - this.logger('(get $done)', this.result); - return this.result[this.result.length - 1] - } - return this.result; - }; - - Object.defineProperties( EventService.prototype, prototypeAccessors ); - - return EventService; -}(NbEventServiceBase)); - -// default - -// create a clone version so we know which one we actually is using -var JsonqlWsEvt = /*@__PURE__*/(function (NBEventService) { - function JsonqlWsEvt() { - NBEventService.call(this, {logger: getDebug('nb-event-service')}); - } - - if ( NBEventService ) JsonqlWsEvt.__proto__ = NBEventService; - JsonqlWsEvt.prototype = Object.create( NBEventService && NBEventService.prototype ); - JsonqlWsEvt.prototype.constructor = JsonqlWsEvt; - - var prototypeAccessors = { name: { configurable: true } }; - - prototypeAccessors.name.get = function () { - return 'jsonql-ws-client' - }; - - Object.defineProperties( JsonqlWsEvt.prototype, prototypeAccessors ); - - return JsonqlWsEvt; -}(EventService)); - -// This is ported back from ws-server and it will get use in the server / client side - -function extractSocketPart(contract) { - if (isKeyInObject(contract, 'socket')) { - return contract.socket; - } - return contract; -} - -/** - * @BUG we should check the socket part instead of expect the downstream to read the menu! - * We only need this when the enableAuth is true otherwise there is only one namespace - * @param {object} contract the socket part of the contract file - * @return {object} 1. remap the contract using the namespace --> resolvers - * 2. the size of the object (1 all private, 2 mixed public with private) - * 3. which namespace is public - */ -function groupByNamespace(contract) { - var socket = extractSocketPart(contract); - - var nspSet = {}; - var size = 0; - var publicNamespace; - for (var resolverName in socket) { - var params = socket[resolverName]; - var namespace = params.namespace; - if (namespace) { - if (!nspSet[namespace]) { - ++size; - nspSet[namespace] = {}; - } - nspSet[namespace][resolverName] = params; - if (!publicNamespace) { - if (params.public) { - publicNamespace = namespace; - } - } - } - } - return { size: size, nspSet: nspSet, publicNamespace: publicNamespace } -} - -// This is ported back from ws-client -// the idea if from https://decembersoft.com/posts/promises-in-serial-with-array-reduce/ -/** - * previously we already make sure the order of the namespaces - * and attach the auth client to it - * @param {array} promises array of unresolved promises - * @return {object} promise resolved with the array of promises resolved results - */ -function chainPromises(promises) { - return promises.reduce(function (promiseChain, currentTask) { return ( - promiseChain.then(function (chainResults) { return ( - currentTask.then(function (currentResult) { return ( - chainResults.concat( [currentResult]) - ); }) - ); }) - ); }, Promise.resolve([])) -} - -/** - * The code was extracted from: - * https://github.com/davidchambers/Base64.js - */ - -var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - -function InvalidCharacterError(message) { - this.message = message; -} - -InvalidCharacterError.prototype = new Error(); -InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - -function polyfill (input) { - var str = String(input).replace(/=+$/, ''); - if (str.length % 4 == 1) { - throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); - } - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = str.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; -} - - -var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; - -function InvalidTokenError(message) { - this.message = message; -} - -InvalidTokenError.prototype = new Error(); -InvalidTokenError.prototype.name = 'InvalidTokenError'; - -var obj$2, obj$1$1, obj$2$1, obj$3, obj$4, obj$5, obj$6, obj$7, obj$8; - -var appProps = { - algorithm: createConfig$1(HSA_ALGO, [STRING_TYPE]), - expiresIn: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$2 = {}, obj$2[ALIAS_KEY] = 'exp', obj$2[OPTIONAL_KEY] = true, obj$2 )), - notBefore: createConfig$1(false, [BOOLEAN_TYPE, NUMBER_TYPE, STRING_TYPE], ( obj$1$1 = {}, obj$1$1[ALIAS_KEY] = 'nbf', obj$1$1[OPTIONAL_KEY] = true, obj$1$1 )), - audience: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$2$1 = {}, obj$2$1[ALIAS_KEY] = 'iss', obj$2$1[OPTIONAL_KEY] = true, obj$2$1 )), - subject: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$3 = {}, obj$3[ALIAS_KEY] = 'sub', obj$3[OPTIONAL_KEY] = true, obj$3 )), - issuer: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$4 = {}, obj$4[ALIAS_KEY] = 'iss', obj$4[OPTIONAL_KEY] = true, obj$4 )), - noTimestamp: createConfig$1(false, [BOOLEAN_TYPE], ( obj$5 = {}, obj$5[OPTIONAL_KEY] = true, obj$5 )), - header: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$6 = {}, obj$6[OPTIONAL_KEY] = true, obj$6 )), - keyid: createConfig$1(false, [BOOLEAN_TYPE, STRING_TYPE], ( obj$7 = {}, obj$7[OPTIONAL_KEY] = true, obj$7 )), - mutatePayload: createConfig$1(false, [BOOLEAN_TYPE], ( obj$8 = {}, obj$8[OPTIONAL_KEY] = true, obj$8 )) -}; - -// ws client using native WebSocket - -function getWS() { - switch(true) { - case (typeof WebSocket !== 'undefined'): - return WebSocket; - case (typeof MozWebSocket !== 'undefined'): - return MozWebSocket; - // case (typeof global !== 'undefined'): - // return global.WebSocket || global.MozWebSocket; - case (typeof window !== 'undefined'): - return window.WebSocket || window.MozWebSocket; - // case (typeof self !== 'undefined'): - // return self.WebSocket || self.MozWebSocket; - default: - throw new JsonqlValidationError('WebSocket is NOT SUPPORTED!') - } -} - -var WS$1 = getWS(); - -// mapping the resolver to their respective nsp -var debug$1 = getDebug('process-contract'); - -/** - * Just make sure the object contain what we are looking for - * @param {object} opts configuration from checkOptions - * @return {object} the target content - */ -var getResolverList = function (contract) { - if (contract) { - var socket = contract.socket; - if (socket) { - return socket; - } - } - throw new JsonqlResolverNotFoundError(MISSING_PROP_ERR) -}; - -/** - * process the contract first - * @param {object} opts configuration - * @return {object} sorted list - */ -function processContract(opts) { - var obj; - - var contract = opts.contract; - var enableAuth = opts.enableAuth; - if (enableAuth) { - return groupByNamespace(contract) - } - return { - nspSet: ( obj = {}, obj[JSONQL_PATH] = getResolverList(contract), obj ), - publicNamespace: JSONQL_PATH, - size: 1 // this prop is pretty meaningless now - } -} - -// export the util methods - -var toArray$1 = function (arg) { return isArray$1(arg) ? arg : [arg]; }; - -/** - * very simple tool to create the event name - * @param {string} [...args] spread - * @return {string} join by _ - */ -var createEvt = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.join('_'); -}; - -/** - * Unbind the event - * @param {object} ee EventEmitter - * @param {string} namespace - * @return {void} - */ -var clearMainEmitEvt = function (ee, namespace) { - var nsps = isArray$1(namespace) ? namespace : [namespace]; - nsps.forEach(function (n) { - ee.$off(createEvt(n, EMIT_EVT)); - }); -}; - -/** - * @param {*} args arguments to send - *@return {object} formatted payload - */ -var formatPayload = function (args) { - var obj; - - return ( - ( obj = {}, obj[QUERY_ARG_NAME] = args, obj ) -); -}; - -/** - * @param {object} nsps namespace as key - * @param {string} type of server - */ -var disconnect = function (nsps, type) { - if ( type === void 0 ) type = JS_WS_SOCKET_IO_NAME; - - try { - var method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate'; - for (var namespace in nsps) { - var nsp = nsps[namespace]; - if (nsp && nsp[method]) { - Reflect.apply(nsp[method], null, []); - } - } - } catch(e) { - // socket.io throw a this.destroy of undefined? - console.error('disconnect', e); - } -}; - -/** - * trigger errors on all the namespace onError handler - * @param {object} ee Event Emitter - * @param {array} namespaces nsps string - * @param {string} message optional - * @return {void} - */ -function triggerNamespacesOnError(ee, namespaces, message) { - namespaces.forEach( function (namespace) { - ee.$call(createEvt(namespace, ERROR_PROP_NAME), [{ message: message, namespace: namespace }]); - }); -} - -// @TODO port what is in the ws-main-handler -var debugFn$1 = getDebug('client-event-handler'); - -/** - * A fake ee handler - * @param {string} namespace nsp - * @param {object} ee EventEmitter - * @return {void} - */ -var notLoginWsHandler = function (namespace, ee) { - ee.$only( - createEvt(namespace, EMIT_EVT), - function(resolverName, args) { - debugFn$1('noLoginHandler hijack the ws call', namespace, resolverName, args); - var error = { - message: NOT_LOGIN_ERR_MSG - }; - // It should just throw error here and should not call the result - // because that's channel for handling normal event not the fake one - ee.$call(createEvt(namespace, resolverName, ERROR_PROP_NAME), [error]); - // also trigger the result handler, but wrap inside the error key - ee.$call(createEvt(namespace, resolverName, RESULT_PROP_NAME), [{ error: error }]); - } - ); -}; - -/** - * centralize all the comm in one place - * @param {object} opts configuration - * @param {array} namespaces namespace(s) - * @param {object} ee Event Emitter instance - * @param {function} bindWsHandler binding the ee to ws - * @param {array} namespaces array of namespace available - * @param {object} nsps namespaced nsp - * @return {void} nothing - */ -function clientEventHandler(opts, nspMap, ee, bindWsHandler, namespaces, nsps) { - // loop - // @BUG for io this has to be in order the one with auth need to get call first - // The order of login is very import we need to run a waterfall here to make sure - // one is execute then the other - namespaces.forEach(function (namespace) { - if (nsps[namespace]) { - debugFn$1('call bindWsHandler', namespace); - var args = [namespace, nsps[namespace], ee]; - if (opts.serverType === SOCKET_IO) { - var nspSet = nspMap.nspSet; - args.push(nspSet[namespace]); - args.push(opts); - } - Reflect.apply(bindWsHandler, null, args); - } else { - // a dummy placeholder - notLoginWsHandler(namespace, ee); - } - }); - // this will be available regardless enableAuth - // because the server can log the client out - ee.$on(LOGOUT_EVENT_NAME, function() { - debugFn$1('LOGOUT_EVENT_NAME'); - // disconnect(nsps, opts.serverType) - // we need to issue error to all the namespace onError handler - triggerNamespacesOnError(ee, namespaces, LOGOUT_EVENT_NAME); - // rebind all of the handler to the fake one - namespaces.forEach( function (namespace) { - clearMainEmitEvt(ee, namespace); - // clear out the nsp - nsps[namespace] = false; - // add a NOT LOGIN error if call - notLoginWsHandler(namespace, ee); - }); - }); -} - -// take the ws reply data for use -var debugFn$2 = getDebug('extract-ws-payload'); - -var keys$1 = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ]; - -/** - * @param {object} payload should be string when reply but could be transformed - * @return {boolean} true is OK - */ -var isWsReply = function (payload) { - var data = payload.data; - if (data) { - var result = keys$1.filter(function (key) { return isKeyInObject(data, key); }); - return (result.length === keys$1.length) ? data : false; - } - return false; -}; - -/** - * @param {object} payload This is the entire ws Event Object - * @return {object} false on failed - */ -var extractWsPayload = function (payload) { - var data = payload.data; - var json = isString$1(data) ? JSON.parse(data) : data; - // debugFn('extractWsPayload', json) - var fdata; - if ((fdata = isWsReply(json)) !== false) { - return { - resolverName: fdata[WS_EVT_NAME], - data: fdata[WS_DATA_NAME], - type: fdata[WS_REPLY_TYPE] - }; - } - throw new JsonqlError('payload can not be decoded', payload) -}; - -// the WebSocket main handler -var debugFn$3 = getDebug('ws-main-handler'); - -/** - * under extremely circumstances we might not even have a resolverName, then - * we issue a global error for the developer to catch it - * @param {object} ee event emitter - * @param {string} namespace nsp - * @param {string} resolverName resolver - * @param {object} json decoded payload or error object - */ -var errorTypeHandler = function (ee, namespace, resolverName, json) { - var evt = [namespace]; - if (resolverName) { - debugFn$3(("a global error on " + namespace)); - evt.push(resolverName); - } - evt.push(ERROR_PROP_NAME); - var evtName = Reflect.apply(createEvt, null, evt); - // test if there is a data field - var payload = json.data || json; - ee.$trigger(evtName, [payload]); -}; - -/** - * Binding the even to socket normally - * @param {string} namespace - * @param {object} ws the nsp - * @param {object} ee EventEmitter - * @return {object} promise resolve after the onopen event - */ -function wsMainHandlerAction(namespace, ws, ee) { - // send - ws.onopen = function() { - // we just call the onReady - ee.$call(READY_PROP_NAME, namespace); - // add listener - ee.$only( - createEvt(namespace, EMIT_EVT), - function(resolverName, args) { - debugFn$3('calling server', resolverName, args); - ws.send( - createQueryStr$1(resolverName, args) - ); - } - ); - }; - - // reply - ws.onmessage = function(payload) { - try { - var json = extractWsPayload(payload); - debugFn$3('Hear from server', json); - var resolverName = json.resolverName; - var type = json.type; - switch (type) { - case EMIT_REPLY_TYPE: - var r = ee.$trigger(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), [json]); - debugFn$3(MESSAGE_PROP_NAME, r); - break; - case ACKNOWLEDGE_REPLY_TYPE: - debugFn$3(RESULT_PROP_NAME, json); - var x = ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [json]); - debugFn$3('onResult add to event?', x); - break; - case ERROR_TYPE: - // this is handled error and we won't throw it - // we need to extract the error from json - errorTypeHandler(ee, namespace, resolverName, json); - break; - // @TODO there should be an error type instead of roll into the other two types? TBC - default: - // if this happen then we should throw it and halt the operation all together - debugFn$3('Unhandled event!', json); - errorTypeHandler(ee, namespace, resolverName, json); - // let error = {error: {'message': 'Unhandled event!', type}}; - // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error]) - } - } catch(e) { - errorTypeHandler(ee, namespace, false, e); - } - }; - // when the server close the connection - ws.onclose = function() { - debugFn$3('ws.onclose'); - // @TODO what to do with this - // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) - }; - // listen to the LOGOUT_EVENT_NAME - ee.$on(LOGOUT_EVENT_NAME, function close() { - try { - debugFn$3('terminate ws connection'); - ws.terminate(); - } catch(e) { - debugFn$3('terminate ws error', e); - } - }); -} - -// make this another standalone module -var debugFn$4 = getDebug('ws-create-client'); - -/** - * Because the nsps can be throw away so it doesn't matter the scope - * this will get reuse again - * @param {object} opts configuration - * @param {object} nspMap from contract - * @param {string|null} token whether we have the token at run time - * @return {object} nsps namespace with namespace as key - */ -var createNsps = function(opts, nspMap, token) { - var nspSet = nspMap.nspSet; - var publicNamespace = nspMap.publicNamespace; - var login = false; - var namespaces = []; - var nsps = {}; - // first we need to binding all the events handler - if (opts.enableAuth && opts.useJwt) { - login = true; // just saying we need to listen to login event - namespaces = getNamespaceInOrder(nspSet, publicNamespace); - nsps = namespaces.map(function (namespace, i) { - var obj, obj$1, obj$2; - - if (i === 0) { - if (token) { - opts.token = token; - return ( obj = {}, obj[namespace] = nspAuthClient(namespace, opts), obj ) - } - return ( obj$1 = {}, obj$1[namespace] = false, obj$1 ) - } - return ( obj$2 = {}, obj$2[namespace] = nspClient(namespace, opts), obj$2 ) - }).reduce(function (first, next) { return Object.assign(first, next); }, {}); - } else { - var namespace = getNameFromPayload$1(nspSet); - namespaces.push(namespace); - // standard without login - // the stock version should not have a namespace - nsps[namespace] = nspClient(false, opts); - } - // return - return { nsps: nsps, namespaces: namespaces, login: login } -}; - -/** - * create a ws client - * @param {object} opts configuration - * @param {object} nspMap namespace with resolvers - * @param {object} ee EventEmitter to pass through - * @return {object} what comes in what goes out - */ -function createClient(opts, nspMap, ee) { - // arguments that don't change - var args = [opts, nspMap, ee, wsMainHandlerAction]; - // now create the nsps - var ref = createNsps(opts, nspMap, opts.token); - var nsps = ref.nsps; - var namespaces = ref.namespaces; - var login = ref.login; - // binding the listeners - and it will listen to LOGOUT event - // to unbind itself, and the above call will bind it again - Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])); - // setup listener - if (login) { - ee.$only(LOGIN_EVENT_NAME, function(token) { - disconnect(nsps, JS_WS_NAME); - // @TODO should we trigger error on this one? - // triggerNamespacesOnError(ee, namespaces, LOGIN_EVENT_NAME) - clearMainEmitEvt(ee, namespaces); - debugFn$4('LOGIN_EVENT_NAME', token); - var newNsps = createNsps(opts, nspMap, token); - // rebind it - Reflect.apply( - clientEventHandler, - null, - args.concat([newNsps.namespaces, newNsps.nsps]) - ); - }); - } - // return what input - return { opts: opts, nspMap: nspMap, ee: ee } -} - -// we only need to export one interface from now on - -var debugFn$5 = getDebug('io-main-handler'); - -/** - * @param {object} ee Event Emitter - * @param {string} namespace namespace of this nsp - * @param {string} resolverName resolver to handle this call - * @return {function} capture the result - */ -var resultHandler = function (ee, namespace, resolverName, evt) { - if ( evt === void 0 ) evt = RESULT_PROP_NAME; - - return function (result) { - ee.$trigger(createEvt(namespace, resolverName, evt), [result]); - } -}; - -/** - * @param {object} nspSet resolver list - * @param {object} nsp nsp instance - * @param {object} ee Event Emitter - * @param {string} namespace name of this nsp - * @return {void} - */ -var createResolverListener = function (nspSet, nsp, ee, namespace) { - for (var resolverName in nspSet) { - nsp.on( - resolverName, - resultHandler(ee, namespace, resolverName, MESSAGE_PROP_NAME) - ); - } -}; - -/** - * @param {object} nsp instance - * @param {object} ee Event Emitter - * @param {string} namespace name of this nsp - * @return {void} - */ -var mainEventHandler = function (nsp, ee, namespace) { - ee.$only( - createEvt(namespace, EMIT_EVT), - function resolverEmitHandler(resolverName, args) { - debugFn$5('mainEventHandler', resolverName, args); - nsp.emit( - resolverName, - formatPayload(args), - resultHandler(ee, namespace, resolverName) - ); - } - ); -}; - -/** - * it makes no different at this point if we know its connection establish or not - * We should actually know this before hand before we call here - * @param {string} namespace of this client - * @param {object} socket this is the resolved nsp connection object - * @param {object} ee Event Emitter - * @param {object} nspSet the list of resolvers - * @param {object} opts configuration - */ -function ioMainHandler(namespace, socket, ee, nspSet, opts) { - // the main listener for all the client resolvers - mainEventHandler(socket, ee, namespace); - // it doesn't make much different between inside the connect or not - // loop through to create the listeners - createResolverListener(nspSet, socket, ee, namespace); - //@TODO next we need to add a ERROR handler - // The server side is not implementing a global ERROR call yet - // and the result or message error will be handle individually by their callback - // listen to the server close event - socket.on('disconnect', function disconnect() { - debugFn$5('io.disconnect'); - // TBC what to do with this - // ee.$trigger(LOGOUT_EVENT_NAME, [namespace]) - }); - // listen to the logout event - ee.$on(LOGOUT_EVENT_NAME, function logoutHandler() { - try { - debugFn$5('terminate ws connection'); - socket.close(); - } catch(e) { - debugFn$5('terminate ws error', e); - } - }); - // the last one to fire - ee.$trigger(READY_PROP_NAME, namespace); -} - -// this will create the socket.io client -var debugFn$6 = getDebug('io-create-client'); - -// just to make it less ugly -var mapNsps = function (nsps, namespaces) { return nsps - .map(function (nsp, i) { - var obj; - - return (( obj = {}, obj[namespaces[i]] = nsp, obj )); - }) - .reduce(function (last, next) { return Object.assign(last,next); }, {}); }; - -/** - * This one will run the create nsps in sequence and make sure - * the auth one connect before we call the others - * @param {object} opts configuration - * @param {object} nspMap contract map - * @param {string} token validation - * @return {object} promise resolve with namespaces, nsps in same order array - */ -var createAuthNsps = function(opts, nspMap, token, namespaces) { - var publicNamespace = nspMap.publicNamespace; - opts.token = token; - var p1 = function () { return nspAuthClient(namespaces[0], opts); }; - var p2 = function () { return nspClient(namespaces[1], opts); }; - return chainPromises([p1(), p2()]) - .then(function (nsps) { return ({ - nsps: mapNsps(nsps, namespaces), - namespaces: namespaces, - login: false - }); }) -}; - -/** - * Because the nsps can be throw away so it doesn't matter the scope - * this will get reuse again - * @param {object} opts configuration - * @param {object} nspMap from contract - * @param {string|null} token whether we have the token at run time - * @return {object} nsps namespace with namespace as key - */ -var createNsps$1 = function(opts, nspMap, token) { - var nspSet = nspMap.nspSet; - var publicNamespace = nspMap.publicNamespace; - var login = false; - // first we need to binding all the events handler - if (opts.enableAuth && opts.useJwt) { - var namespaces = getNamespaceInOrder(nspSet, publicNamespace); - debugFn$6('namespaces', namespaces); - login = opts.useJwt; // just saying we need to listen to login event - if (token) { - debugFn$6('call createAuthNsps'); - return createAuthNsps(opts, nspMap, token, namespaces) - } - debugFn$6('init with a placeholder'); - return nspClient(publicNamespace, opts) - .then(function (nsp) { - var obj; - - return ({ - nsps: ( obj = {}, obj[ publicNamespace ] = nsp, obj[ namespaces[0] ] = false, obj ), - namespaces: namespaces, - login: login - }); - }) - } - // standard without login - // the stock version should not have a namespace - return nspClient(false, opts) - .then(function (nsp) { - var obj; - - return ({ - nsps: ( obj = {}, obj[publicNamespace] = nsp, obj ), - namespaces: [publicNamespace], - login: login - }); - }) -}; - - - -/** - * This is just copy of the ws version we need to figure - * out how to deal with the roundtrip login later - * @param {object} opts configuration - * @param {object} nspMap namespace with resolvers - * @param {object} ee EventEmitter to pass through - * @return {object} what comes in what goes out - */ -function createClient$1(opts, nspMap, ee) { - // arguments don't change - var args = [opts, nspMap, ee, ioMainHandler]; - return createNsps$1(opts, nspMap, opts.token) - .then( function (ref) { - var nsps = ref.nsps; - var namespaces = ref.namespaces; - var login = ref.login; - - // binding the listeners - and it will listen to LOGOUT event - // to unbind itself, and the above call will bind it again - Reflect.apply(clientEventHandler, null, args.concat([namespaces, nsps])); - if (login) { - ee.$only(LOGIN_EVENT_NAME, function(token) { - // here we should disconnect all the previous nsps - disconnect(nsps); - // first trigger a LOGOUT event to unbind ee to ws - // ee.$trigger(LOGOUT_EVENT_NAME) // <-- this seems to cause a lot of problems - clearMainEmitEvt(ee, namespaces); - debugFn$6('LOGIN_EVENT_NAME'); - createNsps$1(opts, nspMap, token) - .then(function (newNsps) { - // rebind it - Reflect.apply( - clientEventHandler, - null, - args.concat([newNsps.namespaces, newNsps.nsps]) - ); - }); - }); - } - // return this will also works because the outter call are in promise chain - return { opts: opts, nspMap: nspMap, ee: ee } - }) -} - -/** - * get the create client instance function - * @param {string} type of client - * @return {function} the actual methods - * @public - */ -function createSocketClient(opts, nspMap, ee) { - switch (opts.serverType) { - case SOCKET_IO: - return createClient$1(opts, nspMap, ee) - case WS: - return createClient(opts, nspMap, ee) - default: - throw new JsonqlError(SOCKET_NOT_DEFINE_ERR) - } -} - -// generator resolvers -var EMIT_EVT$1 = EMIT_EVT; -var UNKNOWN_RESULT$1 = UNKNOWN_RESULT; -var MY_NAMESPACE$1 = MY_NAMESPACE; -var debugFn$7 = getDebug('generator'); - -/** - * prepare the methods - * @param {object} opts configuration - * @param {object} nspMap resolvers index by their namespace - * @param {object} ee EventEmitter - * @return {object} of resolvers - * @public - */ -function generator(opts, nspMap, ee) { - var obj = {}; - var nspSet = nspMap.nspSet; - for (var namespace in nspSet) { - var list = nspSet[namespace]; - for (var resolverName in list) { - var params = list[resolverName]; - var fn = createResolver(ee, namespace, resolverName, params); - obj[resolverName] = setupResolver(namespace, resolverName, params, fn, ee); - } - } - // add error handler - createNamespaceErrorHandler(obj, ee, nspSet); - // add onReady handler - createOnReadyhandler(obj, ee); - // Auth related methods - createAuthMethods(obj, ee, opts); - // this is a helper method for the developer to know the namespace inside - obj.getNsp = function () { - return Object.keys(nspSet) - }; - // output - return obj; -} - -/** - * create the actual function to send message to server - * @param {object} ee EventEmitter instance - * @param {string} namespace this resolver end point - * @param {string} resolverName name of resolver as event name - * @param {object} params from contract - * @return {function} resolver - */ -function createResolver(ee, namespace, resolverName, params) { - // note we pass the new withResult=true option - return function() { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return validateAsync$1(args, params.params, true) - .then( function (_args) { return actionCall(ee, namespace, resolverName, _args); } ) - .catch(finalCatch) - } -} - -/** - * just wrapper - * @param {object} ee EventEmitter - * @param {string} namespace where this belongs - * @param {string} resolverName resolver - * @param {array} args arguments - * @return {void} nothing - */ -function actionCall(ee, namespace, resolverName, args) { - if ( args === void 0 ) args = []; - - debugFn$7(("actionCall: " + namespace + " " + resolverName), args); - ee.$trigger(createEvt(namespace, EMIT_EVT$1), [ - resolverName, - toArray$1(args) - ]); -} - -/** - * break out to use in different places to handle the return from server - * @param {object} data from server - * @param {function} resolver from promise - * @param {function} rejecter from promise - * @return {void} nothing - */ -function respondHandler(data, resolver, rejecter) { - if (isKeyInObject(data, 'error')) { - debugFn$7('rejecter called', data.error); - rejecter(data.error); - } else if (isKeyInObject(data, 'data')) { - debugFn$7('resolver called', data.data); - resolver(data.data); - } else { - debugFn$7('UNKNOWN_RESULT', data); - rejecter({message: UNKNOWN_RESULT$1, error: data}); - } -} - -/** - * Add extra property to the resolver - * @param {string} namespace where this belongs - * @param {string} resolverName name as event name - * @param {object} params from contract - * @param {function} fn resolver function - * @param {object} ee EventEmitter - * @return {function} resolver - */ -var setupResolver = function (namespace, resolverName, params, fn, ee) { - // also need to setup a getter to get back the namespace of this resolver - if (Object.getOwnPropertyDescriptor(fn, MY_NAMESPACE$1) === undefined) { - Object.defineProperty(fn, MY_NAMESPACE$1, { - value: namespace, - writeable: false - }); - } - // onResult handler - if (Object.getOwnPropertyDescriptor(fn, RESULT_PROP_NAME) === undefined) { - Object.defineProperty(fn, RESULT_PROP_NAME, { - set: function(resultCallback) { - if (typeof resultCallback === 'function') { - ee.$only( - createEvt(namespace, resolverName, RESULT_PROP_NAME), - function resultHandler(result) { - respondHandler(result, resultCallback, function (error) { - ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error); - }); - } - ); - } - }, - get: function() { - return null; - } - }); - } - // we do need to add the send prop back because it's the only way to deal with - // bi-directional data stream - if (Object.getOwnPropertyDescriptor(fn, MESSAGE_PROP_NAME) === undefined) { - Object.defineProperty(fn, MESSAGE_PROP_NAME, { - set: function(messageCallback) { - // we expect this to be a function - if (typeof messageCallback === 'function') { - // did that add to the callback - var onMessageCallback = function (args) { - respondHandler(args, messageCallback, function (error) { - ee.$trigger(createEvt(namespace, resolverName, ERROR_PROP_NAME), error); - }); - }; - // register the handler for this message event - ee.$only(createEvt(namespace, resolverName, MESSAGE_PROP_NAME), onMessageCallback); - } - }, - get: function() { - return null; // just return nothing - } - }); - } - // add an ERROR_PROP_NAME handler - if (Object.getOwnPropertyDescriptor(fn, ERROR_PROP_NAME) === undefined) { - Object.defineProperty(fn, ERROR_PROP_NAME, { - set: function(resolverErrorHandler) { - if (typeof resolverErrorHandler === 'function') { - // please note ERROR_PROP_NAME can add multiple listners - ee.$only(createEvt(namespace, resolverName, ERROR_PROP_NAME), resolverErrorHandler); - } - }, - get: function() { - return null; - } - }); - } - // pairing with the server vesrion SEND_MSG_PROP_NAME - if (Object.getOwnPropertyDescriptor(fn, SEND_MSG_PROP_NAME) === undefined) { - Object.defineProperty(fn, SEND_MSG_PROP_NAME, { - set: function(messagePayload) { - var result = validateSync$1(toArray$1(messagePayload), params.params, true); - // here is the different we don't throw erro instead we trigger an - // onError - if (result[ERROR_KEY] && result[ERROR_KEY].length) { - ee.$call( - createEvt(namespace, resolverName, ERROR_PROP_NAME), - [JsonqlValidationError(resolverName, result[ERROR_KEY])] - ); - } else { - // there is no return only an action call - actionCall(ee, namespace, resolverName, result[DATA_KEY]); - } - }, - get: function() { - return null; // just return nothing - } - }); - } - return fn; -}; - -/** - * The problem is the namespace can have more than one - * and we only have on onError message - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} nspSet namespace keys - * @return {void} - */ -var createNamespaceErrorHandler = function (obj, ee, nspSet) { - // using the onError as name - // @TODO we should follow the convention earlier - // make this a setter for the obj itself - if (Object.getOwnPropertyDescriptor(obj, ERROR_PROP_NAME) === undefined) { - Object.defineProperty(obj, ERROR_PROP_NAME, { - set: function(namespaceErrorHandler) { - if (typeof namespaceErrorHandler === 'function') { - // please note ERROR_PROP_NAME can add multiple listners - for (var namespace in nspSet) { - // this one is very tricky, we need to make sure the trigger is calling - // with the namespace as well as the error - ee.$on(createEvt(namespace, ERROR_PROP_NAME), namespaceErrorHandler); - } - } - }, - get: function() { - return null; - } - }); - } -}; - -/** - * This event will fire when the socket.io.on('connection') and ws.onopen - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} nspSet namespace keys - * @return {void} - */ -var createOnReadyhandler = function (obj, ee, nspSet) { - if (Object.getOwnPropertyDescriptor(obj, READY_PROP_NAME) === undefined) { - Object.defineProperty(obj, READY_PROP_NAME, { - set: function(onReadyCallback) { - if (typeof onReadyCallback === 'function') { - // reduce it down to just one flat level - var result = ee.$on(READY_PROP_NAME, onReadyCallback); - } - }, - get: function() { - return null; - } - }); - } -}; - -/** - * Create auth related methods - * @param {object} obj the client itself - * @param {object} ee Event Emitter - * @param {object} opts configuration - * @return {void} - */ -var createAuthMethods = function (obj, ee, opts) { - if (opts.enableAuth) { - // create an additonal login handler - // we require the token - obj[opts.loginHandlerName] = function (token) { - debugFn$7(opts.loginHandlerName, token); - if (token && isString$1(token)) { - return ee.$trigger(LOGIN_EVENT_NAME, [token]) - } - throw new JsonqlValidationError(opts.loginHandlerName) - }; - // logout event handler - obj[opts.logoutHandlerName] = function () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - ee.$trigger(LOGOUT_EVENT_NAME, args); - }; - } -}; - -// main api to get the ws-client - -/** - * The main interface to create the wsClient for use - * @param {function} clientGenerator this is an internal way to generate node or browser client - * @return {function} wsClient - * @public - */ -function main(clientGenerator) { - /** - * @param {object} config configuration - * @param {object} [eventEmitter=false] this will be the bridge between clients - * @return {object} wsClient - */ - var wsClient = function (config, eventEmitter) { - if ( eventEmitter === void 0 ) eventEmitter = false; - - return checkOptions(config) - .then(function (opts) { return ({ - opts: opts, - nspMap: processContract(opts), - ee: eventEmitter || new JsonqlWsEvt() - }); } - ) - .then(clientGenerator) - .then( - function (ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - return createSocketClient(opts, nspMap, ee); - } - ) - .then( - function (ref) { - var opts = ref.opts; - var nspMap = ref.nspMap; - var ee = ref.ee; - - return generator(opts, nspMap, ee); - } - ) - .catch(function (err) { - console.error('jsonql-ws-client init error', err); - }) - }; - // use the Object.addProperty trick - Object.defineProperty(wsClient, 'CLIENT_TYPE_INFO', { - value: 'version: 1.0.0-beta.2 module: cjs', - writable: false - }); - return wsClient; -} - -module.exports = main; -- Gitee From 6cce3b2a6402315b6a00662e0f33f527517296a9 Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 16 Oct 2019 21:48:39 +0800 Subject: [PATCH 17/24] mapping the toArray to the export --- packages/utils/index.js | 2 ++ packages/utils/module.js | 1 + packages/utils/package.json | 2 +- packages/utils/tests/fn.test.js | 2 ++ packages/ws-client/src/core/client-event-handler.js | 3 ++- packages/ws-client/src/core/generator.js | 5 +++-- packages/ws-client/src/core/map-event-to-client.js | 1 + .../ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js | 1 + packages/ws-client/tests/test-node.test.js | 6 +++++- 9 files changed, 18 insertions(+), 5 deletions(-) diff --git a/packages/utils/index.js b/packages/utils/index.js index 628732a6..7173ae84 100644 --- a/packages/utils/index.js +++ b/packages/utils/index.js @@ -16,6 +16,7 @@ import { isContract, // alias // generic inArray, + toArray, isKeyInObject, dasherize, createEvt, @@ -108,6 +109,7 @@ export { isContract, // alias // generic inArray, + toArray, isKeyInObject, dasherize, createEvt, diff --git a/packages/utils/module.js b/packages/utils/module.js index 634bad55..eb75d5f8 100644 --- a/packages/utils/module.js +++ b/packages/utils/module.js @@ -68,6 +68,7 @@ export { isContract, // alias // generic inArray, + toArray, isKeyInObject, dasherize, createEvt, diff --git a/packages/utils/package.json b/packages/utils/package.json index a78cdf29..92c14aaa 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-utils", - "version": "0.7.5", + "version": "0.7.6", "description": "This is a jsonql dependency module, not for generate use.", "main": "main.js", "module": "index.js", diff --git a/packages/utils/tests/fn.test.js b/packages/utils/tests/fn.test.js index b6a2766f..62d93104 100644 --- a/packages/utils/tests/fn.test.js +++ b/packages/utils/tests/fn.test.js @@ -5,4 +5,6 @@ const utilFns = require('../main') test(`It should have certain functions in the export`, t => { t.truthy(utilFns.groupByNamespace) + + t.truthy(utilFns.toArray) }) diff --git a/packages/ws-client/src/core/client-event-handler.js b/packages/ws-client/src/core/client-event-handler.js index 4a37e69d..c6c3f510 100644 --- a/packages/ws-client/src/core/client-event-handler.js +++ b/packages/ws-client/src/core/client-event-handler.js @@ -29,7 +29,7 @@ const notLoginWsHandler = (namespace, ee) => { ee.$only( createEvt(namespace, EMIT_EVT), function(resolverName, args) { - debugFn('noLoginHandler hijack the ws call', namespace, resolverName, args) + debugFn('notLoginHandler hijack the ws call', namespace, resolverName, args) let error = { message: NOT_LOGIN_ERR_MSG } @@ -61,6 +61,7 @@ export default function clientEventHandler(opts, nspMap, ee, bindWsHandler, name if (nsps[namespace]) { debugFn('call bindWsHandler', namespace) let args = [namespace, nsps[namespace], ee] + // @TODO do we need to keep this? if (opts.serverType === SOCKET_IO) { let { nspSet } = nspMap; args.push(nspSet[namespace]) diff --git a/packages/ws-client/src/core/generator.js b/packages/ws-client/src/core/generator.js index 974b9dba..3e7f5de6 100644 --- a/packages/ws-client/src/core/generator.js +++ b/packages/ws-client/src/core/generator.js @@ -96,8 +96,9 @@ function createResolver(ee, namespace, resolverName, params) { * @return {void} nothing */ function actionCall(ee, namespace, resolverName, args = []) { - debugFn(`actionCall: ${namespace} ${resolverName}`, args) - ee.$trigger(createEvt(namespace, EMIT_EVT), [ + const eventName = createEvt(namespace, EMIT_EVT) + debugFn(`actionCall: ${eventName} --> ${resolverName}`, args) + ee.$trigger(eventName, [ resolverName, toArray(args) ]) diff --git a/packages/ws-client/src/core/map-event-to-client.js b/packages/ws-client/src/core/map-event-to-client.js index a0c11505..483f31d4 100644 --- a/packages/ws-client/src/core/map-event-to-client.js +++ b/packages/ws-client/src/core/map-event-to-client.js @@ -56,6 +56,7 @@ const createNsps = function(opts, nspMap, token) { if (opts.enableAuth && opts.useJwt) { let namespaces = getNamespaceInOrder(nspSet, publicNamespace) debugFn('namespaces', namespaces) + // @TODO this is no longer valid the useJwt is always true login = opts.useJwt; // just saying we need to listen to login event if (token) { debugFn('call createAuthNsps') diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js index 8939ef20..42c16a38 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js @@ -53,6 +53,7 @@ const errorTypeHandler = (ee, namespace, resolverName, json) => { export default function wsMainHandlerAction(namespace, ws, ee) { // send ws.onopen = function() { + debugFn('onopen listened') // we just call the onReady ee.$call(READY_PROP_NAME, namespace) // add listener diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index 78de4dfe..2be75b42 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -58,9 +58,13 @@ test.serial.cb('The ws client can connect to the WebSocket server public interfa .then(msg => { // @NOTE perhaps I should consider when return the // the promise, I could also return the socket object for use as well - debug(msg) t.pass() t.end() }) + .catch(err => { + debug(err) + t.pass() + t.end() + }) }) -- Gitee From 6cb909ca819ece37cf7aba24e0bc31569ba1fb0a Mon Sep 17 00:00:00 2001 From: joelchu Date: Wed, 16 Oct 2019 22:08:22 +0800 Subject: [PATCH 18/24] jsonql-utils to 0.7.6 --- packages/utils/browser.js | 2 +- packages/utils/main.js | 2 +- packages/utils/main.js.map | 2 +- packages/ws-client/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/utils/browser.js b/packages/utils/browser.js index 9d9c13bb..1594f308 100644 --- a/packages/utils/browser.js +++ b/packages/utils/browser.js @@ -1,2 +1,2 @@ -!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p="[object Null]",v="[object Undefined]",d=i?i.toStringTag:void 0;function y(t){return null==t?void 0===t?v:p:d&&d in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var h,b,g=(h=Object.getPrototypeOf,b=Object,function(t){return h(b(t))});function _(t){return null!=t&&"object"==typeof t}var j="[object Object]",m=Function.prototype,O=Object.prototype,w=m.toString,P=O.hasOwnProperty,S=w.call(Object);function A(t){if(!_(t)||y(t)!=j)return!1;var r=g(t);if(null===r)return!0;var e=P.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var N="[object Symbol]";var E=1/0,k=i?i.prototype:void 0,z=k?k.toString:void 0;function F(t){if("string"==typeof t)return t;if(r(t))return function(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(t,r){for(var e=t.length;e--&&C(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var K="[object String]";function W(t){return"string"==typeof t||!r(t)&&_(t)&&y(t)==K}function Z(t,r){return t===r||t!=t&&r!=r}function X(t,r){for(var e=t.length;e--;)if(Z(t[e][0],r))return e;return-1}var Y=Array.prototype.splice;function tt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},tt.prototype.set=function(t,r){var e=this.__data__,n=X(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var et="[object AsyncFunction]",nt="[object Function]",ot="[object GeneratorFunction]",ut="[object Proxy]";function it(t){if(!rt(t))return!1;var r=y(t);return r==nt||r==ot||r==et||r==ut}var at,ct=u["__core-js_shared__"],ft=(at=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+at:"";var st=Function.prototype.toString;var lt=/^\[object .+?Constructor\]$/,pt=Function.prototype,vt=Object.prototype,dt=pt.toString,yt=vt.hasOwnProperty,ht=RegExp("^"+dt.call(yt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function bt(t){return!(!rt(t)||function(t){return!!ft&&ft in t}(t))&&(it(t)?ht:lt).test(function(t){if(null!=t){try{return st.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function gt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return bt(e)?e:void 0}var _t=gt(u,"Map"),jt=gt(Object,"create");var mt="__lodash_hash_undefined__",Ot=Object.prototype.hasOwnProperty;var wt=Object.prototype.hasOwnProperty;var Pt="__lodash_hash_undefined__";function St(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Zt}function Yt(t){return null!=t&&Xt(t.length)&&!it(t)}var tr="object"==typeof t&&t&&!t.nodeType&&t,rr=tr&&"object"==typeof module&&module&&!module.nodeType&&module,er=rr&&rr.exports===tr?u.Buffer:void 0,nr=(er?er.isBuffer:void 0)||function(){return!1},or={};or["[object Float32Array]"]=or["[object Float64Array]"]=or["[object Int8Array]"]=or["[object Int16Array]"]=or["[object Int32Array]"]=or["[object Uint8Array]"]=or["[object Uint8ClampedArray]"]=or["[object Uint16Array]"]=or["[object Uint32Array]"]=!0,or["[object Arguments]"]=or["[object Array]"]=or["[object ArrayBuffer]"]=or["[object Boolean]"]=or["[object DataView]"]=or["[object Date]"]=or["[object Error]"]=or["[object Function]"]=or["[object Map]"]=or["[object Number]"]=or["[object Object]"]=or["[object RegExp]"]=or["[object Set]"]=or["[object String]"]=or["[object WeakMap]"]=!1;var ur="object"==typeof t&&t&&!t.nodeType&&t,ir=ur&&"object"==typeof module&&module&&!module.nodeType&&module,ar=ir&&ir.exports===ur&&n.process,cr=function(){try{var t=ir&&ir.require&&ir.require("util").types;return t||ar&&ar.binding&&ar.binding("util")}catch(t){}}(),fr=cr&&cr.isTypedArray,sr=fr?function(t){return function(r){return t(r)}}(fr):function(t){return _(t)&&Xt(t.length)&&!!or[y(t)]};function lr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var pr=Object.prototype.hasOwnProperty;function vr(t,r,e){var n=t[r];pr.call(t,r)&&Z(n,e)&&(void 0!==e||r in t)||Ft(t,r,e)}var dr=9007199254740991,yr=/^(?:0|[1-9]\d*)$/;function hr(t,r){var e=typeof t;return!!(r=null==r?dr:r)&&("number"==e||"symbol"!=e&&yr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=kr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Er);function Tr(t,r){return xr(function(t,r,e){return r=Nr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Nr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Cr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!rt(e))return!1;var n=typeof r;return!!("number"==n?Yt(e)&&hr(r,e.length):"string"==n&&r in e)&&Z(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,[t])}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):Jr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.checkIsContract=re,t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=ae,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(ae(t,r,e,n))},t.createQuery=ie,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(ie(t,r,e))},t.dasherize=function(t){return H(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case $r:return t[Gr];case Br:return[t[Qr],t[Vr]];default:throw new te("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Xr(e,r);return n}catch(t){throw new Xr(e,t)}},t.extractSocketPart=ee,t.formatPayload=oe,t.getCallMethod=function(t){switch(!0){case t===Hr[0]:return $r;case t===Hr[1]:return Br;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=se,t.getMutationFromPayload=function(t){var r=fe(t,se);if(!1!==r)return r;throw new Yr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ue,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=ce,t.getQueryFromPayload=function(t){var r=fe(t,ce);if(!1!==r)return r;throw new Yr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=ee(t);if(!1===e){if(r)return t;throw new te("socket not found in contract!")}var n,o={},u=0;for(var i in e){var a=e[i],c=a.namespace;c&&(o[c]||(++u,o[c]={}),o[c][i]=a,n||a.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},t.inArray=Mr,t.injectToFn=function(t,r,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)},t.isContract=pe,t.isJsonqlErrorObj=le,t.isKeyInObject=Rr,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==H(t)},t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=le(t)||u,o))},t.packResult=function(t){var r;return JSON.stringify(((r={}).data=t,r))},t.resultHandler=function(t){return Rr(t,"data")&&!Rr(t,"error")?t.data:t},t.timestamp=Ur,t.toJson=function(t){return"string"==typeof t?function(t){try{return JSON.parse(t)}catch(r){return t}}(t):JSON.parse(JSON.stringify(t))},t.toPayload=ne,t.urlParams=qr,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((t=t||self).jsonqlUtils={})}(this,(function(t){"use strict";var r=Array.isArray,e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="object"==typeof e&&e&&e.Object===Object&&e,o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")(),i=u.Symbol,a=Object.prototype,c=a.hasOwnProperty,f=a.toString,s=i?i.toStringTag:void 0;var l=Object.prototype.toString;var p="[object Null]",v="[object Undefined]",d=i?i.toStringTag:void 0;function y(t){return null==t?void 0===t?v:p:d&&d in Object(t)?function(t){var r=c.call(t,s),e=t[s];try{t[s]=void 0;var n=!0}catch(t){}var o=f.call(t);return n&&(r?t[s]=e:delete t[s]),o}(t):function(t){return l.call(t)}(t)}var h,b,g=(h=Object.getPrototypeOf,b=Object,function(t){return h(b(t))});function _(t){return null!=t&&"object"==typeof t}var j="[object Object]",m=Function.prototype,O=Object.prototype,w=m.toString,P=O.hasOwnProperty,S=w.call(Object);function A(t){if(!_(t)||y(t)!=j)return!1;var r=g(t);if(null===r)return!0;var e=P.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var N="[object Symbol]";var E=1/0,k=i?i.prototype:void 0,z=k?k.toString:void 0;function F(t){if("string"==typeof t)return t;if(r(t))return function(t,r){for(var e=-1,n=null==t?0:t.length,o=Array(n);++e=n?t:function(t,r,e){var n=-1,o=t.length;r<0&&(r=-r>o?0:o+r),(e=e>o?o:e)<0&&(e+=o),o=r>e?0:e-r>>>0,r>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(t,r){for(var e=t.length;e--&&C(r,t[e],0)>-1;);return e}(o,u)+1).join("")}var K="[object String]";function W(t){return"string"==typeof t||!r(t)&&_(t)&&y(t)==K}function Z(t,r){return t===r||t!=t&&r!=r}function X(t,r){for(var e=t.length;e--;)if(Z(t[e][0],r))return e;return-1}var Y=Array.prototype.splice;function tt(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},tt.prototype.set=function(t,r){var e=this.__data__,n=X(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this};var et="[object AsyncFunction]",nt="[object Function]",ot="[object GeneratorFunction]",ut="[object Proxy]";function it(t){if(!rt(t))return!1;var r=y(t);return r==nt||r==ot||r==et||r==ut}var at,ct=u["__core-js_shared__"],ft=(at=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+at:"";var st=Function.prototype.toString;var lt=/^\[object .+?Constructor\]$/,pt=Function.prototype,vt=Object.prototype,dt=pt.toString,yt=vt.hasOwnProperty,ht=RegExp("^"+dt.call(yt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function bt(t){return!(!rt(t)||function(t){return!!ft&&ft in t}(t))&&(it(t)?ht:lt).test(function(t){if(null!=t){try{return st.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function gt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return bt(e)?e:void 0}var _t=gt(u,"Map"),jt=gt(Object,"create");var mt="__lodash_hash_undefined__",Ot=Object.prototype.hasOwnProperty;var wt=Object.prototype.hasOwnProperty;var Pt="__lodash_hash_undefined__";function St(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1&&t%1==0&&t<=Zt}function Yt(t){return null!=t&&Xt(t.length)&&!it(t)}var tr="object"==typeof t&&t&&!t.nodeType&&t,rr=tr&&"object"==typeof module&&module&&!module.nodeType&&module,er=rr&&rr.exports===tr?u.Buffer:void 0,nr=(er?er.isBuffer:void 0)||function(){return!1},or={};or["[object Float32Array]"]=or["[object Float64Array]"]=or["[object Int8Array]"]=or["[object Int16Array]"]=or["[object Int32Array]"]=or["[object Uint8Array]"]=or["[object Uint8ClampedArray]"]=or["[object Uint16Array]"]=or["[object Uint32Array]"]=!0,or["[object Arguments]"]=or["[object Array]"]=or["[object ArrayBuffer]"]=or["[object Boolean]"]=or["[object DataView]"]=or["[object Date]"]=or["[object Error]"]=or["[object Function]"]=or["[object Map]"]=or["[object Number]"]=or["[object Object]"]=or["[object RegExp]"]=or["[object Set]"]=or["[object String]"]=or["[object WeakMap]"]=!1;var ur="object"==typeof t&&t&&!t.nodeType&&t,ir=ur&&"object"==typeof module&&module&&!module.nodeType&&module,ar=ir&&ir.exports===ur&&n.process,cr=function(){try{var t=ir&&ir.require&&ir.require("util").types;return t||ar&&ar.binding&&ar.binding("util")}catch(t){}}(),fr=cr&&cr.isTypedArray,sr=fr?function(t){return function(r){return t(r)}}(fr):function(t){return _(t)&&Xt(t.length)&&!!or[y(t)]};function lr(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var pr=Object.prototype.hasOwnProperty;function vr(t,r,e){var n=t[r];pr.call(t,r)&&Z(n,e)&&(void 0!==e||r in t)||Ft(t,r,e)}var dr=9007199254740991,yr=/^(?:0|[1-9]\d*)$/;function hr(t,r){var e=typeof t;return!!(r=null==r?dr:r)&&("number"==e||"symbol"!=e&&yr.test(t))&&t>-1&&t%1==0&&t0){if(++r>=kr)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(Er);function Tr(t,r){return xr(function(t,r,e){return r=Nr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=Nr(n.length-r,0),i=Array(u);++o1?r[n-1]:void 0,u=n>2?r[2]:void 0;for(o=Cr.length>3&&"function"==typeof o?(n--,o):void 0,u&&function(t,r,e){if(!rt(e))return!1;var n=typeof r;return!!("number"==n?Yt(e)&&hr(r,e.length):"string"==n&&r in e)&&Z(e[r],t)}(r[0],r[1],u)&&(o=n<3?void 0:o,n=1),t=Object(t);++e0;)r[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return r.reduce((function(t,r){return Reflect.apply(r,null,[t])}),Reflect.apply(t,null,e))}},t.chainPromises=function(t,r){return void 0===r&&(r=!1),t.reduce((function(t,e){return t.then((function(t){return e.then((function(e){return!1===r?t.concat([e]):Jr(t,e)}))}))}),Promise.resolve(!1===r?[]:A(r)?r:{}))},t.checkIsContract=re,t.createEvt=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];return t.join("_")},t.createMutation=ae,t.createMutationStr=function(t,r,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(ae(t,r,e,n))},t.createQuery=ie,t.createQueryStr=function(t,r,e){return void 0===r&&(r=[]),void 0===e&&(e=!1),JSON.stringify(ie(t,r,e))},t.dasherize=function(t){return H(t).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},t.extractArgsFromPayload=function(t,r){switch(r){case $r:return t[Gr];case Br:return[t[Qr],t[Vr]];default:throw new te("Unknown "+r+" to extract argument from!")}},t.extractParamsFromContract=function(t,r,e){try{var n=t[r][e];if(!n)throw new Xr(e,r);return n}catch(t){throw new Xr(e,t)}},t.extractSocketPart=ee,t.formatPayload=oe,t.getCallMethod=function(t){switch(!0){case t===Hr[0]:return $r;case t===Hr[1]:return Br;default:return!1}},t.getConfigValue=function(t,r){return r&&A(r)&&t in r?r[t]:void 0},t.getMutationFromArgs=se,t.getMutationFromPayload=function(t){var r=fe(t,se);if(!1!==r)return r;throw new Yr("[getMutationArgs] Payload is malformed!",t)},t.getNameFromPayload=ue,t.getNamespaceInOrder=function(t,r){var e=[];for(var n in t)n===r?e[1]=n:e[0]=n;return e},t.getQueryFromArgs=ce,t.getQueryFromPayload=function(t){var r=fe(t,ce);if(!1!==r)return r;throw new Yr("[getQueryArgs] Payload is malformed!",t)},t.groupByNamespace=function(t,r){void 0===r&&(r=!1);var e=ee(t);if(!1===e){if(r)return t;throw new te("socket not found in contract!")}var n,o={},u=0;for(var i in e){var a=e[i],c=a.namespace;c&&(o[c]||(++u,o[c]={}),o[c][i]=a,n||a.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},t.inArray=Mr,t.injectToFn=function(t,r,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(t,r);return!1===n&&void 0!==o?t:(Object.defineProperty(t,r,{value:e,writable:n}),t)},t.isContract=pe,t.isJsonqlErrorObj=le,t.isKeyInObject=Rr,t.isNotEmpty=function(t){return void 0!==t&&!1!==t&&null!==t&&""!==H(t)},t.objDefineProps=function(t,r,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(t,r)&&Object.defineProperty(t,r,{set:e,get:null===n?function(){return null}:n}),t},t.packError=function(t,r,e,n){var o;void 0===r&&(r="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var u={detail:t,className:r,statusCode:e,message:n};return JSON.stringify(((o={}).error=le(t)||u,o))},t.packResult=function(t){var r;return JSON.stringify(((r={}).data=t,r))},t.resultHandler=function(t){return Rr(t,"data")&&!Rr(t,"error")?t.data:t},t.timestamp=Ur,t.toArray=function(t){return r(t)?t:[t]},t.toJson=function(t){return"string"==typeof t?function(t){try{return JSON.parse(t)}catch(r){return t}}(t):JSON.parse(JSON.stringify(t))},t.toPayload=ne,t.urlParams=qr,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=browser.js.map diff --git a/packages/utils/main.js b/packages/utils/main.js index 6d8169fa..ce542001 100644 --- a/packages/utils/main.js +++ b/packages/utils/main.js @@ -1,2 +1,2 @@ -"use strict";function _interopDefault(r){return r&&"object"==typeof r&&"default"in r?r.default:r}Object.defineProperty(exports,"__esModule",{value:!0});var fs=_interopDefault(require("fs")),path=require("path"),isArray=Array.isArray,global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},freeGlobal="object"==typeof global$1&&global$1&&global$1.Object===Object&&global$1,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol?Symbol.toStringTag:void 0;function getRawTag(r){var t=hasOwnProperty.call(r,symToStringTag),e=r[symToStringTag];try{r[symToStringTag]=void 0;var n=!0}catch(r){}var o=nativeObjectToString.call(r);return n&&(t?r[symToStringTag]=e:delete r[symToStringTag]),o}var objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString;function objectToString(r){return nativeObjectToString$1.call(r)}var nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag$1=Symbol?Symbol.toStringTag:void 0;function baseGetTag(r){return null==r?void 0===r?undefinedTag:nullTag:symToStringTag$1&&symToStringTag$1 in Object(r)?getRawTag(r):objectToString(r)}function overArg(r,t){return function(e){return r(t(e))}}var getPrototype=overArg(Object.getPrototypeOf,Object);function isObjectLike(r){return null!=r&&"object"==typeof r}var objectTag="[object Object]",funcProto=Function.prototype,objectProto$2=Object.prototype,funcToString=funcProto.toString,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectCtorString=funcToString.call(Object);function isPlainObject(r){if(!isObjectLike(r)||baseGetTag(r)!=objectTag)return!1;var t=getPrototype(r);if(null===t)return!0;var e=hasOwnProperty$1.call(t,"constructor")&&t.constructor;return"function"==typeof e&&e instanceof e&&funcToString.call(e)==objectCtorString}function arrayMap(r,t){for(var e=-1,n=null==r?0:r.length,o=Array(n);++eo?0:o+t),(e=e>o?o:e)<0&&(e+=o),o=t>e?0:e-t>>>0,t>>>=0;for(var a=Array(o);++n=n?r:baseSlice(r,t,e)}function baseFindIndex(r,t,e,n){for(var o=r.length,a=e+(n?1:-1);n?a--:++a-1;);return e}function charsStartIndex(r,t){for(var e=-1,n=r.length;++e-1;);return e}function asciiToArray(r){return r.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(r){return reHasUnicode.test(r)}var rsAstralRange$1="\\ud800-\\udfff",rsComboMarksRange$1="\\u0300-\\u036f",reComboHalfMarksRange$1="\\ufe20-\\ufe2f",rsComboSymbolsRange$1="\\u20d0-\\u20ff",rsComboRange$1=rsComboMarksRange$1+reComboHalfMarksRange$1+rsComboSymbolsRange$1,rsVarRange$1="\\ufe0e\\ufe0f",rsAstral="["+rsAstralRange$1+"]",rsCombo="["+rsComboRange$1+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange$1+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ$1="\\u200d",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange$1+"]?",rsOptJoin="(?:"+rsZWJ$1+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(r){return r.match(reUnicode)||[]}function stringToArray(r){return hasUnicode(r)?unicodeToArray(r):asciiToArray(r)}function toString(r){return null==r?"":baseToString(r)}var reTrim=/^\s+|\s+$/g;function trim(r,t,e){if((r=toString(r))&&(e||void 0===t))return r.replace(reTrim,"");if(!r||!(t=baseToString(t)))return r;var n=stringToArray(r),o=stringToArray(t);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var stringTag="[object String]";function isString(r){return"string"==typeof r||!isArray(r)&&isObjectLike(r)&&baseGetTag(r)==stringTag}function listCacheClear(){this.__data__=[],this.size=0}function eq(r,t){return r===t||r!=r&&t!=t}function assocIndexOf(r,t){for(var e=r.length;e--;)if(eq(r[e][0],t))return e;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(r){var t=this.__data__,e=assocIndexOf(t,r);return!(e<0)&&(e==t.length-1?t.pop():splice.call(t,e,1),--this.size,!0)}function listCacheGet(r){var t=this.__data__,e=assocIndexOf(t,r);return e<0?void 0:t[e][1]}function listCacheHas(r){return assocIndexOf(this.__data__,r)>-1}function listCacheSet(r,t){var e=this.__data__,n=assocIndexOf(e,r);return n<0?(++this.size,e.push([r,t])):e[n][1]=t,this}function ListCache(r){var t=-1,e=null==r?0:r.length;for(this.clear();++t-1&&r%1==0&&r<=MAX_SAFE_INTEGER}function isArrayLike(r){return null!=r&&isLength(r.length)&&!isFunction(r)}function isArrayLikeObject(r){return isObjectLike(r)&&isArrayLike(r)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag$1="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag$1="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(r){return isObjectLike(r)&&isLength(r.length)&&!!typedArrayTags[baseGetTag(r)]}function baseUnary(r){return function(t){return r(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag$1]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag$1]=typedArrayTags[weakMapTag]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var r=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return r||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(r){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(r,t){if(("constructor"!==t||"function"!=typeof r[t])&&"__proto__"!=t)return r[t]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(r,t,e){var n=r[t];hasOwnProperty$6.call(r,t)&&eq(n,e)&&(void 0!==e||t in r)||baseAssignValue(r,t,e)}function copyObject(r,t,e,n){var o=!e;e||(e={});for(var a=-1,i=t.length;++a-1&&r%1==0&&r0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return r.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(r,t){return setToString(overRest(r,t,identity),r+"")}function isIterateeCall(r,t,e){if(!isObject(e))return!1;var n=typeof t;return!!("number"==n?isArrayLike(e)&&isIndex(t,e.length):"string"==n&&t in e)&&eq(e[t],r)}function createAssigner(r){return baseRest((function(t,e){var n=-1,o=e.length,a=o>1?e[o-1]:void 0,i=o>2?e[2]:void 0;for(a=r.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(e[0],e[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++n0;)t[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return t.reduce((function(r,t){return Reflect.apply(t,null,[r])}),Reflect.apply(r,null,e))}};function chainPromises(r,t){return void 0===t&&(t=!1),r.reduce((function(r,e){return r.then((function(r){return e.then((function(e){return!1===t?r.concat([e]):merge(r,e)}))}))}),Promise.resolve(!1===t?[]:isPlainObject(t)?t:{}))}function objDefineProps(r,t,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(r,t)&&Object.defineProperty(r,t,{set:e,get:null===n?function(){return null}:n}),r}function injectToFn(r,t,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(r,t);return!1===n&&void 0!==o?r:(Object.defineProperty(r,t,{value:e,writable:n}),r)}var inArray=function(r,t){return!!r.filter((function(r){return r===t})).length},parse=function(r){try{return JSON.parse(r)}catch(t){return r}},isKeyInObject=function(r,t){var e=Object.keys(r);return inArray(e,t)},createEvt=function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.join("_")},timestamp=function(r){void 0===r&&(r=!1);var t=Date.now();return r?Math.floor(t/1e3):t},urlParams=function(r,t){var e=[];for(var n in t)e.push([n,t[n]].join("="));return[r,e.join("&")].join("?")},cacheBurstUrl=function(r){return urlParams(r,cacheBurst())},cacheBurst=function(){return{_cb:timestamp()}},dasherize=function(r){return trim(r).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},getConfigValue=function(r,t){return t&&isPlainObject(t)&&r in t?t[r]:void 0},toJson=function(r){return"string"==typeof r?parse(r):JSON.parse(JSON.stringify(r))},isNotEmpty=function(r){return void 0!==r&&!1!==r&&null!==r&&""!==trim(r)},EXT="js",DATA_KEY="data",ERROR_KEY="error",CONTENT_TYPE="application/vnd.api+json",QUERY_NAME="query",MUTATION_NAME="mutation",SOCKET_NAME="socket",PAYLOAD_PARAM_NAME="payload",CONDITION_PARAM_NAME="condition",RESOLVER_PARAM_NAME="resolverName",QUERY_ARG_NAME="args",API_REQUEST_METHODS=["POST","PUT"],INDEX_KEY="index",NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,BASE64_FORMAT="base64",SUCCESS_STATUS=200,FORBIDDEN_STATUS=403;function getErrorByStatus(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}}var Jsonql406Error=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),Jsonql500Error=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),JsonqlAuthorisationError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),JsonqlContractAuthError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),JsonqlResolverAppError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),isBrowser=function(){try{if(window||document)return!0}catch(r){}return!1},isNode=function(){try{if(!isBrowser()&&global$1)return!0}catch(r){}return!1};function whereAmI(){return isBrowser()?"browser":isNode()?"node":"unknown"}var JsonqlBaseError=function(r){function t(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t)}return r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t,t.where=function(){return whereAmI()},t}(Error),JsonqlResolverNotFoundError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlEnumError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),JsonqlTypeError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),JsonqlCheckerError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),JsonqlValidationError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlServerError=function(r){function t(e,n){r.call(this,n),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),errors=Object.freeze({__proto__:null,Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError}),JsonqlError$1=JsonqlError,isKeyInObject$1=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};function clientErrorsHandler(r){if(isKeyInObject$1(r,"error")){var t=r.error,e=t.className,n=t.name,o=e||n,a=t.message||NO_ERROR_MSG,i=t.detail||t;if(o&&errors[o])throw new errors[e](a,i);throw new JsonqlError$1(a,i)}return r}var UNKNOWN_ERROR="unknown";function mapErrToName(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}function getErrorNameByInstance(r,t){var e=mapErrToName(r,t);return e.length?e[0]:UNKNOWN_ERROR}function getErrorNameByInstanceWithDefault(r,t){var e=getErrorNameByInstance(r,t);return e===UNKNOWN_ERROR?"JsonqlError":e}function finalCatch(r){if(Array.isArray(r))throw new JsonqlValidationError("",r);var t=r.message||NO_ERROR_MSG,e=r.detail||r;switch(!0){case r instanceof Jsonql406Error:throw new Jsonql406Error(t,e);case r instanceof Jsonql500Error:throw new Jsonql500Error(t,e);case r instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(t,e);case r instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(t,e);case r instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(t,e);case r instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(t,e);case r instanceof JsonqlEnumError:throw new JsonqlEnumError(t,e);case r instanceof JsonqlTypeError:throw new JsonqlTypeError(t,e);case r instanceof JsonqlCheckerError:throw new JsonqlCheckerError(t,e);case r instanceof JsonqlValidationError:throw new JsonqlValidationError(t,e);case r instanceof JsonqlServerError:throw new JsonqlServerError(t,e);default:throw new JsonqlError(t,e)}}var JSONQL_ERRORS_INFO="__PLACEHOLDER__",jsonqlErrors=Object.freeze({__proto__:null,JSONQL_ERRORS_INFO:JSONQL_ERRORS_INFO,UNKNOWN_ERROR:UNKNOWN_ERROR,getErrorByStatus:getErrorByStatus,clientErrorsHandler:clientErrorsHandler,finalCatch:finalCatch,getErrorNameByInstance:getErrorNameByInstance,getErrorNameByInstanceWithDefault:getErrorNameByInstanceWithDefault,Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError});function checkIsContract(r){return isPlainObject(r)&&(isKeyInObject(r,QUERY_NAME)||isKeyInObject(r,MUTATION_NAME)||isKeyInObject(r,SOCKET_NAME))}function extractSocketPart(r){return!!isKeyInObject(r,"socket")&&r.socket}function groupByNamespace(r,t){void 0===t&&(t=!1);var e=extractSocketPart(r);if(!1===e){if(t)return r;throw new JsonqlError("socket not found in contract!")}var n,o={},a=0;for(var i in e){var s=e[i],u=s.namespace;u&&(o[u]||(++a,o[u]={}),o[u][i]=s,n||s.public&&(n=u))}return{size:a,nspSet:o,publicNamespace:n}}function getNamespaceInOrder(r,t){var e=[];for(var n in r)n===t?e[1]=n:e[0]=n;return e}function extractArgsFromPayload(r,t){switch(t){case QUERY_NAME:return r[QUERY_ARG_NAME];case MUTATION_NAME:return[r[PAYLOAD_PARAM_NAME],r[CONDITION_PARAM_NAME]];default:throw new JsonqlError("Unknown "+t+" to extract argument from!")}}function extractParamsFromContract(r,t,e){try{var n=r[t][e];if(!n)throw new JsonqlResolverNotFoundError(e,t);return n}catch(r){throw new JsonqlResolverNotFoundError(e,r)}}var toPayload=function(r){return isString(r)?JSON.parse(r):r},formatPayload=function(r){var t;return(t={})[QUERY_ARG_NAME]=r,t};function getNameFromPayload(r){return Object.keys(r)[0]}function createQuery(r,t,e){var n;if(void 0===t&&(t=[]),void 0===e&&(e=!1),isString(r)&&isArray(t)){var o=formatPayload(t);return!0===e?o:((n={})[r]=o,n)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:r,args:t})}function createQueryStr(r,t,e){return void 0===t&&(t=[]),void 0===e&&(e=!1),JSON.stringify(createQuery(r,t,e))}function createMutation(r,t,e,n){var o;void 0===e&&(e={}),void 0===n&&(n=!1);var a={};if(a[PAYLOAD_PARAM_NAME]=t,a[CONDITION_PARAM_NAME]=e,!0===n)return a;if(isString(r))return(o={})[r]=a,o;throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:r,payload:t,condition:e})}function createMutationStr(r,t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(createMutation(r,t,e,n))}function getQueryFromArgs(r,t){var e;if(r&&isPlainObject(t)){var n=t[r];if(n[QUERY_ARG_NAME])return(e={})[RESOLVER_PARAM_NAME]=r,e[QUERY_ARG_NAME]=n[QUERY_ARG_NAME],e}return!1}function processPayload(r,t){var e=toPayload(r),n=getNameFromPayload(e);return Reflect.apply(t,null,[n,e])}function getQueryFromPayload(r){var t=processPayload(r,getQueryFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",r)}function getMutationFromArgs(r,t){var e;if(r&&isPlainObject(t)){var n=t[r];if(n)return(e={})[RESOLVER_PARAM_NAME]=r,e[PAYLOAD_PARAM_NAME]=n[PAYLOAD_PARAM_NAME],e[CONDITION_PARAM_NAME]=n[CONDITION_PARAM_NAME],e}return!1}function getMutationFromPayload(r){var t=processPayload(r,getMutationFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",r)}var getCallMethod=function(r){var t=API_REQUEST_METHODS[0],e=API_REQUEST_METHODS[1];switch(!0){case r===t:return QUERY_NAME;case r===e:return MUTATION_NAME;default:return!1}},packResult=function(r){var t;return JSON.stringify(((t={})[DATA_KEY]=r,t))},isJsonqlErrorObj=function(r){return!!["detail","className"].filter((function(t){return isKeyInObject(r,t)})).length&&["className","message","statusCode"].filter((function(t){return isKeyInObject(r,t)})).map((function(t){var e;return(e={})[t]="object"==typeof r[t]?r[t].toString():r[t],e})).reduce(merge,{detail:r.toString()})},packError=function(r,t,e,n){var o;void 0===t&&(t="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var a={detail:r,className:t,statusCode:e,message:n};return JSON.stringify(((o={})[ERROR_KEY]=isJsonqlErrorObj(r)||a,o))},resultHandler=function(r){return isKeyInObject(r,DATA_KEY)&&!isKeyInObject(r,ERROR_KEY)?r[DATA_KEY]:r},isContract=checkIsContract,VERSION="0.7.5",lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,e=r.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===r[s-2]?2:"="===r[s-1]?1:0,i=new Arr(3*s/4-a),n=a>0?s-4:s;var u=0;for(t=0,e=0;t>16&255,i[u++]=o>>8&255,i[u++]=255&o;return 2===a?(o=revLookup[r.charCodeAt(t)]<<2|revLookup[r.charCodeAt(t+1)]>>4,i[u++]=255&o):1===a&&(o=revLookup[r.charCodeAt(t)]<<10|revLookup[r.charCodeAt(t+1)]<<4|revLookup[r.charCodeAt(t+2)]>>2,i[u++]=o>>8&255,i[u++]=255&o),i}function tripletToBase64(r){return lookup[r>>18&63]+lookup[r>>12&63]+lookup[r>>6&63]+lookup[63&r]}function encodeChunk(r,t,e){for(var n,o=[],a=t;as?s:i+16383));return 1===n?(t=r[e-1],o+=lookup[t>>2],o+=lookup[t<<4&63],o+="=="):2===n&&(t=(r[e-2]<<8)+r[e-1],o+=lookup[t>>10],o+=lookup[t>>4&63],o+=lookup[t<<2&63],o+="="),a.push(o),a.join("")}function read(r,t,e,n,o){var a,i,s=8*o-n-1,u=(1<>1,c=-7,l=e?o-1:0,p=e?-1:1,h=r[t+l];for(l+=p,a=h&(1<<-c)-1,h>>=-c,c+=s;c>0;a=256*a+r[t+l],l+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+r[t+l],l+=p,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(h?-1:1);i+=Math.pow(2,n),a-=f}return(h?-1:1)*i*Math.pow(2,a-n)}function write(r,t,e,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?p/u:p*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;r[e+h]=255&s,h+=g,s/=256,o-=8);for(i=i<0;r[e+h]=255&i,h+=g,i/=256,f-=8);r[e+h-g]|=128*y}var toString$1={}.toString,isArray$1=Array.isArray||function(r){return"[object Array]"==toString$1.call(r)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer$2.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(r,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|r}function internalIsBuffer(r){return!(null==r||!r._isBuffer)}function byteLength(r,t){if(internalIsBuffer(r))return r.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer))return r.byteLength;"string"!=typeof r&&(r=""+r);var e=r.length;if(0===e)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return utf8ToBytes(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return base64ToBytes(r).length;default:if(n)return utf8ToBytes(r).length;t=(""+t).toLowerCase(),n=!0}}function slowToString(r,t,e){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(t>>>=0))return"";for(r||(r="utf8");;)switch(r){case"hex":return hexSlice(this,t,e);case"utf8":case"utf-8":return utf8Slice(this,t,e);case"ascii":return asciiSlice(this,t,e);case"latin1":case"binary":return latin1Slice(this,t,e);case"base64":return base64Slice(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,e);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}function swap(r,t,e){var n=r[t];r[t]=r[e],r[e]=n}function bidirectionalIndexOf(r,t,e,n,o){if(0===r.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:r.length-1),e<0&&(e=r.length+e),e>=r.length){if(o)return-1;e=r.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof t&&(t=Buffer$2.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(r,t,e,n,o);if("number"==typeof t)return t&=255,Buffer$2.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(r,t,e):Uint8Array.prototype.lastIndexOf.call(r,t,e):arrayIndexOf(r,[t],e,n,o);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(r,t,e,n,o){var a,i=1,s=r.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(r.length<2||t.length<2)return-1;i=2,s/=2,u/=2,e/=2}function f(r,t){return 1===i?r[t]:r.readUInt16BE(t*i)}if(o){var c=-1;for(a=e;as&&(e=s-u),a=e;a>=0;a--){for(var l=!0,p=0;po&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=e)switch(l){case 1:f<128&&(c=f);break;case 2:128==(192&(a=r[o+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=r[o+1],i=r[o+2],128==(192&a)&&128==(192&i)&&(u=(15&f)<<12|(63&a)<<6|63&i)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=r[o+1],i=r[o+2],s=r[o+3],128==(192&a)&&128==(192&i)&&128==(192&s)&&(u=(15&f)<<18|(63&a)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,l=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=l}return decodeCodePointsArray(n)}Buffer$2.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer$2.poolSize=8192,Buffer$2._augment=function(r){return r.__proto__=Buffer$2.prototype,r},Buffer$2.from=function(r,t,e){return from(null,r,t,e)},Buffer$2.TYPED_ARRAY_SUPPORT&&(Buffer$2.prototype.__proto__=Uint8Array.prototype,Buffer$2.__proto__=Uint8Array),Buffer$2.alloc=function(r,t,e){return alloc(null,r,t,e)},Buffer$2.allocUnsafe=function(r){return allocUnsafe$1(null,r)},Buffer$2.allocUnsafeSlow=function(r){return allocUnsafe$1(null,r)},Buffer$2.isBuffer=isBuffer$1,Buffer$2.compare=function(r,t){if(!internalIsBuffer(r)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(r===t)return 0;for(var e=r.length,n=t.length,o=0,a=Math.min(e,n);o0&&(r=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(r+=" ... ")),""},Buffer$2.prototype.compare=function(r,t,e,n,o){if(!internalIsBuffer(r))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===e&&(e=r?r.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||e>r.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=e)return 0;if(n>=o)return-1;if(t>=e)return 1;if(this===r)return 0;for(var a=(o>>>=0)-(n>>>=0),i=(e>>>=0)-(t>>>=0),s=Math.min(a,i),u=this.slice(n,o),f=r.slice(t,e),c=0;co)&&(e=o),r.length>0&&(e<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return hexWrite(this,r,t,e);case"utf8":case"utf-8":return utf8Write(this,r,t,e);case"ascii":return asciiWrite(this,r,t,e);case"latin1":case"binary":return latin1Write(this,r,t,e);case"base64":return base64Write(this,r,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,r,t,e);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Buffer$2.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(r){var t=r.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,r);for(var e="",n=0;nn)&&(e=n);for(var o="",a=t;ae)throw new RangeError("Trying to access beyond buffer length")}function checkInt(r,t,e,n,o,a){if(!internalIsBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||tr.length)throw new RangeError("Index out of range")}function objectWriteUInt16(r,t,e,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(r.length-e,2);o>>8*(n?o:1-o)}function objectWriteUInt32(r,t,e,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(r.length-e,4);o>>8*(n?o:3-o)&255}function checkIEEE754(r,t,e,n,o,a){if(e+n>r.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function writeFloat(r,t,e,n,o){return o||checkIEEE754(r,t,e,4),write(r,t,e,n,23,4),e+4}function writeDouble(r,t,e,n,o){return o||checkIEEE754(r,t,e,8),write(r,t,e,n,52,8),e+8}Buffer$2.prototype.slice=function(r,t){var e,n=this.length;if((r=~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[r+--t]*o;return n},Buffer$2.prototype.readUInt8=function(r,t){return t||checkOffset(r,1,this.length),this[r]},Buffer$2.prototype.readUInt16LE=function(r,t){return t||checkOffset(r,2,this.length),this[r]|this[r+1]<<8},Buffer$2.prototype.readUInt16BE=function(r,t){return t||checkOffset(r,2,this.length),this[r]<<8|this[r+1]},Buffer$2.prototype.readUInt32LE=function(r,t){return t||checkOffset(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+16777216*this[r+3]},Buffer$2.prototype.readUInt32BE=function(r,t){return t||checkOffset(r,4,this.length),16777216*this[r]+(this[r+1]<<16|this[r+2]<<8|this[r+3])},Buffer$2.prototype.readIntLE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=this[r],o=1,a=0;++a=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer$2.prototype.readIntBE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=t,o=1,a=this[r+--n];n>0&&(o*=256);)a+=this[r+--n]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},Buffer$2.prototype.readInt8=function(r,t){return t||checkOffset(r,1,this.length),128&this[r]?-1*(255-this[r]+1):this[r]},Buffer$2.prototype.readInt16LE=function(r,t){t||checkOffset(r,2,this.length);var e=this[r]|this[r+1]<<8;return 32768&e?4294901760|e:e},Buffer$2.prototype.readInt16BE=function(r,t){t||checkOffset(r,2,this.length);var e=this[r+1]|this[r]<<8;return 32768&e?4294901760|e:e},Buffer$2.prototype.readInt32LE=function(r,t){return t||checkOffset(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},Buffer$2.prototype.readInt32BE=function(r,t){return t||checkOffset(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},Buffer$2.prototype.readFloatLE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!0,23,4)},Buffer$2.prototype.readFloatBE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!1,23,4)},Buffer$2.prototype.readDoubleLE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!0,52,8)},Buffer$2.prototype.readDoubleBE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!1,52,8)},Buffer$2.prototype.writeUIntLE=function(r,t,e,n){(r=+r,t|=0,e|=0,n)||checkInt(this,r,t,e,Math.pow(2,8*e)-1,0);var o=1,a=0;for(this[t]=255&r;++a=0&&(a*=256);)this[t+o]=r/a&255;return t+e},Buffer$2.prototype.writeUInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,255,0),Buffer$2.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[t]=255&r,t+1},Buffer$2.prototype.writeUInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer$2.prototype.writeUInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer$2.prototype.writeUInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t+3]=r>>>24,this[t+2]=r>>>16,this[t+1]=r>>>8,this[t]=255&r):objectWriteUInt32(this,r,t,!0),t+4},Buffer$2.prototype.writeUInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>24,this[t+1]=r>>>16,this[t+2]=r>>>8,this[t+3]=255&r):objectWriteUInt32(this,r,t,!1),t+4},Buffer$2.prototype.writeIntLE=function(r,t,e,n){if(r=+r,t|=0,!n){var o=Math.pow(2,8*e-1);checkInt(this,r,t,e,o-1,-o)}var a=0,i=1,s=0;for(this[t]=255&r;++a>0)-s&255;return t+e},Buffer$2.prototype.writeIntBE=function(r,t,e,n){if(r=+r,t|=0,!n){var o=Math.pow(2,8*e-1);checkInt(this,r,t,e,o-1,-o)}var a=e-1,i=1,s=0;for(this[t+a]=255&r;--a>=0&&(i*=256);)r<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(r/i>>0)-s&255;return t+e},Buffer$2.prototype.writeInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,127,-128),Buffer$2.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[t]=255&r,t+1},Buffer$2.prototype.writeInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer$2.prototype.writeInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer$2.prototype.writeInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8,this[t+2]=r>>>16,this[t+3]=r>>>24):objectWriteUInt32(this,r,t,!0),t+4},Buffer$2.prototype.writeInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>24,this[t+1]=r>>>16,this[t+2]=r>>>8,this[t+3]=255&r):objectWriteUInt32(this,r,t,!1),t+4},Buffer$2.prototype.writeFloatLE=function(r,t,e){return writeFloat(this,r,t,!0,e)},Buffer$2.prototype.writeFloatBE=function(r,t,e){return writeFloat(this,r,t,!1,e)},Buffer$2.prototype.writeDoubleLE=function(r,t,e){return writeDouble(this,r,t,!0,e)},Buffer$2.prototype.writeDoubleBE=function(r,t,e){return writeDouble(this,r,t,!1,e)},Buffer$2.prototype.copy=function(r,t,e,n){if(e||(e=0),n||0===n||(n=this.length),t>=r.length&&(t=r.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),r.length-t=0;--o)r[o+t]=this[o+e];else if(a<1e3||!Buffer$2.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,r||(r=0),"number"==typeof r)for(a=t;a55295&&e<57344){if(!o){if(e>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=e;continue}if(e<56320){(t-=3)>-1&&a.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,e<128){if((t-=1)<0)break;a.push(e)}else if(e<2048){if((t-=2)<0)break;a.push(e>>6|192,63&e|128)}else if(e<65536){if((t-=3)<0)break;a.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return a}function asciiToBytes(r){for(var t=[],e=0;e>8,o=e%256,a.push(o),a.push(n);return a}function base64ToBytes(r){return toByteArray(base64clean(r))}function blitBuffer(r,t,e,n){for(var o=0;o=t.length||o>=r.length);++o)t[o+e]=r[o];return o}function isnan(r){return r!=r}function isBuffer$1(r){return null!=r&&(!!r._isBuffer||isFastBuffer(r)||isSlowBuffer(r))}function isFastBuffer(r){return!!r.constructor&&"function"==typeof r.constructor.isBuffer&&r.constructor.isBuffer(r)}function isSlowBuffer(r){return"function"==typeof r.readFloatLE&&"function"==typeof r.slice&&isFastBuffer(r.slice(0,0))}function buff(r,t){return void 0===t&&(t=BASE64_FORMAT),isBuffer$1(r)?r:new Buffer$2.from(r,t)}var replaceErrors=function(r,t){if(t instanceof Error){var e={};return Object.getOwnPropertyNames(t).forEach((function(r){e[r]=t[r]})),e}return t},printError=function(r){return JSON.stringify(r,replaceErrors)};function findFromContract(r,t,e){return!!(e[r]&&e[r][t]&&e[r][t].file&&fs.existsSync(e[r][t].file))&&e[r][t].file}var DOT=".",getDocLen=function(r){return Buffer$2.byteLength(r,"utf8")},headerParser=function(r,t){try{var e=r.headers.accept.split(",");return t?e.filter((function(r){return r===t})):e}catch(r){return[]}},isHeaderPresent=function(r,t){return!!headerParser(r,t).length},getPathToFn=function(r,t,e){var n=e.resolverDir,o=dasherize(r),a=[];e.contract&&e.contract[t]&&e.contract[t].path&&a.push(e.contract[t].path),a.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),a.push(path.join(n,t,[o,EXT].join(DOT)));for(var i=a.length,s=0;so?0:o+t),(e=e>o?o:e)<0&&(e+=o),o=t>e?0:e-t>>>0,t>>>=0;for(var a=Array(o);++n=n?r:baseSlice(r,t,e)}function baseFindIndex(r,t,e,n){for(var o=r.length,a=e+(n?1:-1);n?a--:++a-1;);return e}function charsStartIndex(r,t){for(var e=-1,n=r.length;++e-1;);return e}function asciiToArray(r){return r.split("")}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(r){return reHasUnicode.test(r)}var rsAstralRange$1="\\ud800-\\udfff",rsComboMarksRange$1="\\u0300-\\u036f",reComboHalfMarksRange$1="\\ufe20-\\ufe2f",rsComboSymbolsRange$1="\\u20d0-\\u20ff",rsComboRange$1=rsComboMarksRange$1+reComboHalfMarksRange$1+rsComboSymbolsRange$1,rsVarRange$1="\\ufe0e\\ufe0f",rsAstral="["+rsAstralRange$1+"]",rsCombo="["+rsComboRange$1+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange$1+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ$1="\\u200d",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange$1+"]?",rsOptJoin="(?:"+rsZWJ$1+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(r){return r.match(reUnicode)||[]}function stringToArray(r){return hasUnicode(r)?unicodeToArray(r):asciiToArray(r)}function toString(r){return null==r?"":baseToString(r)}var reTrim=/^\s+|\s+$/g;function trim(r,t,e){if((r=toString(r))&&(e||void 0===t))return r.replace(reTrim,"");if(!r||!(t=baseToString(t)))return r;var n=stringToArray(r),o=stringToArray(t);return castSlice(n,charsStartIndex(n,o),charsEndIndex(n,o)+1).join("")}var stringTag="[object String]";function isString(r){return"string"==typeof r||!isArray(r)&&isObjectLike(r)&&baseGetTag(r)==stringTag}function listCacheClear(){this.__data__=[],this.size=0}function eq(r,t){return r===t||r!=r&&t!=t}function assocIndexOf(r,t){for(var e=r.length;e--;)if(eq(r[e][0],t))return e;return-1}var arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(r){var t=this.__data__,e=assocIndexOf(t,r);return!(e<0)&&(e==t.length-1?t.pop():splice.call(t,e,1),--this.size,!0)}function listCacheGet(r){var t=this.__data__,e=assocIndexOf(t,r);return e<0?void 0:t[e][1]}function listCacheHas(r){return assocIndexOf(this.__data__,r)>-1}function listCacheSet(r,t){var e=this.__data__,n=assocIndexOf(e,r);return n<0?(++this.size,e.push([r,t])):e[n][1]=t,this}function ListCache(r){var t=-1,e=null==r?0:r.length;for(this.clear();++t-1&&r%1==0&&r<=MAX_SAFE_INTEGER}function isArrayLike(r){return null!=r&&isLength(r.length)&&!isFunction(r)}function isArrayLikeObject(r){return isObjectLike(r)&&isArrayLike(r)}function stubFalse(){return!1}var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,Buffer$1=moduleExports$1?root.Buffer:void 0,nativeIsBuffer=Buffer$1?Buffer$1.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag$1="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag$1="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};function baseIsTypedArray(r){return isObjectLike(r)&&isLength(r.length)&&!!typedArrayTags[baseGetTag(r)]}function baseUnary(r){return function(t){return r(t)}}typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag$1]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag$1]=typedArrayTags[weakMapTag]=!1;var freeExports$2="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$2=freeExports$2&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2,freeProcess=moduleExports$2&&freeGlobal.process,nodeUtil=function(){try{var r=freeModule$2&&freeModule$2.require&&freeModule$2.require("util").types;return r||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(r){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;function safeGet(r,t){if(("constructor"!==t||"function"!=typeof r[t])&&"__proto__"!=t)return r[t]}var objectProto$8=Object.prototype,hasOwnProperty$6=objectProto$8.hasOwnProperty;function assignValue(r,t,e){var n=r[t];hasOwnProperty$6.call(r,t)&&eq(n,e)&&(void 0!==e||t in r)||baseAssignValue(r,t,e)}function copyObject(r,t,e,n){var o=!e;e||(e={});for(var a=-1,i=t.length;++a-1&&r%1==0&&r0){if(++t>=HOT_COUNT)return arguments[0]}else t=0;return r.apply(void 0,arguments)}}var setToString=shortOut(baseSetToString);function baseRest(r,t){return setToString(overRest(r,t,identity),r+"")}function isIterateeCall(r,t,e){if(!isObject(e))return!1;var n=typeof t;return!!("number"==n?isArrayLike(e)&&isIndex(t,e.length):"string"==n&&t in e)&&eq(e[t],r)}function createAssigner(r){return baseRest((function(t,e){var n=-1,o=e.length,a=o>1?e[o-1]:void 0,i=o>2?e[2]:void 0;for(a=r.length>3&&"function"==typeof a?(o--,a):void 0,i&&isIterateeCall(e[0],e[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++n0;)t[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return t.reduce((function(r,t){return Reflect.apply(t,null,[r])}),Reflect.apply(r,null,e))}};function chainPromises(r,t){return void 0===t&&(t=!1),r.reduce((function(r,e){return r.then((function(r){return e.then((function(e){return!1===t?r.concat([e]):merge(r,e)}))}))}),Promise.resolve(!1===t?[]:isPlainObject(t)?t:{}))}function objDefineProps(r,t,e,n){return void 0===n&&(n=null),void 0===Object.getOwnPropertyDescriptor(r,t)&&Object.defineProperty(r,t,{set:e,get:null===n?function(){return null}:n}),r}function injectToFn(r,t,e,n){void 0===n&&(n=!1);var o=Object.getOwnPropertyDescriptor(r,t);return!1===n&&void 0!==o?r:(Object.defineProperty(r,t,{value:e,writable:n}),r)}var inArray=function(r,t){return!!r.filter((function(r){return r===t})).length},toArray=function(r){return isArray(r)?r:[r]},parse=function(r){try{return JSON.parse(r)}catch(t){return r}},isKeyInObject=function(r,t){var e=Object.keys(r);return inArray(e,t)},createEvt=function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.join("_")},timestamp=function(r){void 0===r&&(r=!1);var t=Date.now();return r?Math.floor(t/1e3):t},urlParams=function(r,t){var e=[];for(var n in t)e.push([n,t[n]].join("="));return[r,e.join("&")].join("?")},cacheBurstUrl=function(r){return urlParams(r,cacheBurst())},cacheBurst=function(){return{_cb:timestamp()}},dasherize=function(r){return trim(r).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},getConfigValue=function(r,t){return t&&isPlainObject(t)&&r in t?t[r]:void 0},toJson=function(r){return"string"==typeof r?parse(r):JSON.parse(JSON.stringify(r))},isNotEmpty=function(r){return void 0!==r&&!1!==r&&null!==r&&""!==trim(r)},EXT="js",DATA_KEY="data",ERROR_KEY="error",CONTENT_TYPE="application/vnd.api+json",QUERY_NAME="query",MUTATION_NAME="mutation",SOCKET_NAME="socket",PAYLOAD_PARAM_NAME="payload",CONDITION_PARAM_NAME="condition",RESOLVER_PARAM_NAME="resolverName",QUERY_ARG_NAME="args",API_REQUEST_METHODS=["POST","PUT"],INDEX_KEY="index",NO_ERROR_MSG="No message",NO_STATUS_CODE=-1,BASE64_FORMAT="base64",SUCCESS_STATUS=200,FORBIDDEN_STATUS=403;function getErrorByStatus(r,t){switch(void 0===t&&(t=!1),r){case 401:return t?"JsonqlContractAuthError":"JsonqlAuthorisationError";case 403:return"JsonqlForbiddenError";case 404:return"JsonqlResolverNotFoundError";case 406:return"Jsonql406Error";case 500:return"Jsonql500Error";default:return"JsonqlError"}}var Jsonql406Error=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 406},e.name.get=function(){return"Jsonql406Error"},Object.defineProperties(t,e),t}(Error),Jsonql500Error=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"Jsonql500Error"},Object.defineProperties(t,e),t}(Error),JsonqlAuthorisationError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlAuthorisationError"},Object.defineProperties(t,e),t}(Error),JsonqlContractAuthError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 401},e.name.get=function(){return"JsonqlContractAuthError"},Object.defineProperties(t,e),t}(Error),JsonqlResolverAppError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 500},e.name.get=function(){return"JsonqlResolverAppError"},Object.defineProperties(t,e),t}(Error),isBrowser=function(){try{if(window||document)return!0}catch(r){}return!1},isNode=function(){try{if(!isBrowser()&&global$1)return!0}catch(r){}return!1};function whereAmI(){return isBrowser()?"browser":isNode()?"node":"unknown"}var JsonqlBaseError=function(r){function t(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];r.apply(this,t)}return r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t,t.where=function(){return whereAmI()},t}(Error),JsonqlResolverNotFoundError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={statusCode:{configurable:!0},name:{configurable:!0}};return e.statusCode.get=function(){return 404},e.name.get=function(){return"JsonqlResolverNotFoundError"},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlEnumError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlEnumError"},Object.defineProperties(t,e),t}(Error),JsonqlTypeError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlTypeError"},Object.defineProperties(t,e),t}(Error),JsonqlCheckerError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,r.captureStackTrace&&r.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlCheckerError"},Object.defineProperties(t,e),t}(Error),JsonqlValidationError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlValidationError"},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlError=function(r){function t(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];r.apply(this,e),this.message=e[0],this.detail=e[1],this.className=t.name,Error.captureStackTrace&&Error.captureStackTrace(this,t)}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0},statusCode:{configurable:!0}};return e.name.get=function(){return"JsonqlError"},e.statusCode.get=function(){return NO_STATUS_CODE},Object.defineProperties(t,e),t}(JsonqlBaseError),JsonqlServerError=function(r){function t(e,n){r.call(this,n),this.statusCode=e,this.className=t.name}r&&(t.__proto__=r),t.prototype=Object.create(r&&r.prototype),t.prototype.constructor=t;var e={name:{configurable:!0}};return e.name.get=function(){return"JsonqlServerError"},Object.defineProperties(t,e),t}(Error),errors=Object.freeze({__proto__:null,Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError}),JsonqlError$1=JsonqlError,isKeyInObject$1=function(r,t){return!!Object.keys(r).filter((function(r){return t===r})).length};function clientErrorsHandler(r){if(isKeyInObject$1(r,"error")){var t=r.error,e=t.className,n=t.name,o=e||n,a=t.message||NO_ERROR_MSG,i=t.detail||t;if(o&&errors[o])throw new errors[e](a,i);throw new JsonqlError$1(a,i)}return r}var UNKNOWN_ERROR="unknown";function mapErrToName(r,t){return r.filter((function(r){return t instanceof r})).map((function(r){return r.name}))}function getErrorNameByInstance(r,t){var e=mapErrToName(r,t);return e.length?e[0]:UNKNOWN_ERROR}function getErrorNameByInstanceWithDefault(r,t){var e=getErrorNameByInstance(r,t);return e===UNKNOWN_ERROR?"JsonqlError":e}function finalCatch(r){if(Array.isArray(r))throw new JsonqlValidationError("",r);var t=r.message||NO_ERROR_MSG,e=r.detail||r;switch(!0){case r instanceof Jsonql406Error:throw new Jsonql406Error(t,e);case r instanceof Jsonql500Error:throw new Jsonql500Error(t,e);case r instanceof JsonqlAuthorisationError:throw new JsonqlAuthorisationError(t,e);case r instanceof JsonqlContractAuthError:throw new JsonqlContractAuthError(t,e);case r instanceof JsonqlResolverAppError:throw new JsonqlResolverAppError(t,e);case r instanceof JsonqlResolverNotFoundError:throw new JsonqlResolverNotFoundError(t,e);case r instanceof JsonqlEnumError:throw new JsonqlEnumError(t,e);case r instanceof JsonqlTypeError:throw new JsonqlTypeError(t,e);case r instanceof JsonqlCheckerError:throw new JsonqlCheckerError(t,e);case r instanceof JsonqlValidationError:throw new JsonqlValidationError(t,e);case r instanceof JsonqlServerError:throw new JsonqlServerError(t,e);default:throw new JsonqlError(t,e)}}var JSONQL_ERRORS_INFO="__PLACEHOLDER__",jsonqlErrors=Object.freeze({__proto__:null,JSONQL_ERRORS_INFO:JSONQL_ERRORS_INFO,UNKNOWN_ERROR:UNKNOWN_ERROR,getErrorByStatus:getErrorByStatus,clientErrorsHandler:clientErrorsHandler,finalCatch:finalCatch,getErrorNameByInstance:getErrorNameByInstance,getErrorNameByInstanceWithDefault:getErrorNameByInstanceWithDefault,Jsonql406Error:Jsonql406Error,Jsonql500Error:Jsonql500Error,JsonqlAuthorisationError:JsonqlAuthorisationError,JsonqlContractAuthError:JsonqlContractAuthError,JsonqlResolverAppError:JsonqlResolverAppError,JsonqlResolverNotFoundError:JsonqlResolverNotFoundError,JsonqlEnumError:JsonqlEnumError,JsonqlTypeError:JsonqlTypeError,JsonqlCheckerError:JsonqlCheckerError,JsonqlValidationError:JsonqlValidationError,JsonqlError:JsonqlError,JsonqlServerError:JsonqlServerError});function checkIsContract(r){return isPlainObject(r)&&(isKeyInObject(r,QUERY_NAME)||isKeyInObject(r,MUTATION_NAME)||isKeyInObject(r,SOCKET_NAME))}function extractSocketPart(r){return!!isKeyInObject(r,"socket")&&r.socket}function groupByNamespace(r,t){void 0===t&&(t=!1);var e=extractSocketPart(r);if(!1===e){if(t)return r;throw new JsonqlError("socket not found in contract!")}var n,o={},a=0;for(var i in e){var s=e[i],u=s.namespace;u&&(o[u]||(++a,o[u]={}),o[u][i]=s,n||s.public&&(n=u))}return{size:a,nspSet:o,publicNamespace:n}}function getNamespaceInOrder(r,t){var e=[];for(var n in r)n===t?e[1]=n:e[0]=n;return e}function extractArgsFromPayload(r,t){switch(t){case QUERY_NAME:return r[QUERY_ARG_NAME];case MUTATION_NAME:return[r[PAYLOAD_PARAM_NAME],r[CONDITION_PARAM_NAME]];default:throw new JsonqlError("Unknown "+t+" to extract argument from!")}}function extractParamsFromContract(r,t,e){try{var n=r[t][e];if(!n)throw new JsonqlResolverNotFoundError(e,t);return n}catch(r){throw new JsonqlResolverNotFoundError(e,r)}}var toPayload=function(r){return isString(r)?JSON.parse(r):r},formatPayload=function(r){var t;return(t={})[QUERY_ARG_NAME]=r,t};function getNameFromPayload(r){return Object.keys(r)[0]}function createQuery(r,t,e){var n;if(void 0===t&&(t=[]),void 0===e&&(e=!1),isString(r)&&isArray(t)){var o=formatPayload(t);return!0===e?o:((n={})[r]=o,n)}throw new JsonqlValidationError("[createQuery] expect resolverName to be string and args to be array!",{resolverName:r,args:t})}function createQueryStr(r,t,e){return void 0===t&&(t=[]),void 0===e&&(e=!1),JSON.stringify(createQuery(r,t,e))}function createMutation(r,t,e,n){var o;void 0===e&&(e={}),void 0===n&&(n=!1);var a={};if(a[PAYLOAD_PARAM_NAME]=t,a[CONDITION_PARAM_NAME]=e,!0===n)return a;if(isString(r))return(o={})[r]=a,o;throw new JsonqlValidationError("[createMutation] expect resolverName to be string!",{resolverName:r,payload:t,condition:e})}function createMutationStr(r,t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(createMutation(r,t,e,n))}function getQueryFromArgs(r,t){var e;if(r&&isPlainObject(t)){var n=t[r];if(n[QUERY_ARG_NAME])return(e={})[RESOLVER_PARAM_NAME]=r,e[QUERY_ARG_NAME]=n[QUERY_ARG_NAME],e}return!1}function processPayload(r,t){var e=toPayload(r),n=getNameFromPayload(e);return Reflect.apply(t,null,[n,e])}function getQueryFromPayload(r){var t=processPayload(r,getQueryFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getQueryArgs] Payload is malformed!",r)}function getMutationFromArgs(r,t){var e;if(r&&isPlainObject(t)){var n=t[r];if(n)return(e={})[RESOLVER_PARAM_NAME]=r,e[PAYLOAD_PARAM_NAME]=n[PAYLOAD_PARAM_NAME],e[CONDITION_PARAM_NAME]=n[CONDITION_PARAM_NAME],e}return!1}function getMutationFromPayload(r){var t=processPayload(r,getMutationFromArgs);if(!1!==t)return t;throw new JsonqlValidationError("[getMutationArgs] Payload is malformed!",r)}var getCallMethod=function(r){var t=API_REQUEST_METHODS[0],e=API_REQUEST_METHODS[1];switch(!0){case r===t:return QUERY_NAME;case r===e:return MUTATION_NAME;default:return!1}},packResult=function(r){var t;return JSON.stringify(((t={})[DATA_KEY]=r,t))},isJsonqlErrorObj=function(r){return!!["detail","className"].filter((function(t){return isKeyInObject(r,t)})).length&&["className","message","statusCode"].filter((function(t){return isKeyInObject(r,t)})).map((function(t){var e;return(e={})[t]="object"==typeof r[t]?r[t].toString():r[t],e})).reduce(merge,{detail:r.toString()})},packError=function(r,t,e,n){var o;void 0===t&&(t="JsonqlError"),void 0===e&&(e=0),void 0===n&&(n="");var a={detail:r,className:t,statusCode:e,message:n};return JSON.stringify(((o={})[ERROR_KEY]=isJsonqlErrorObj(r)||a,o))},resultHandler=function(r){return isKeyInObject(r,DATA_KEY)&&!isKeyInObject(r,ERROR_KEY)?r[DATA_KEY]:r},isContract=checkIsContract,VERSION="0.7.6",lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,inited=!1;function init(){inited=!0;for(var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,e=r.length;t0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===r[s-2]?2:"="===r[s-1]?1:0,i=new Arr(3*s/4-a),n=a>0?s-4:s;var u=0;for(t=0,e=0;t>16&255,i[u++]=o>>8&255,i[u++]=255&o;return 2===a?(o=revLookup[r.charCodeAt(t)]<<2|revLookup[r.charCodeAt(t+1)]>>4,i[u++]=255&o):1===a&&(o=revLookup[r.charCodeAt(t)]<<10|revLookup[r.charCodeAt(t+1)]<<4|revLookup[r.charCodeAt(t+2)]>>2,i[u++]=o>>8&255,i[u++]=255&o),i}function tripletToBase64(r){return lookup[r>>18&63]+lookup[r>>12&63]+lookup[r>>6&63]+lookup[63&r]}function encodeChunk(r,t,e){for(var n,o=[],a=t;as?s:i+16383));return 1===n?(t=r[e-1],o+=lookup[t>>2],o+=lookup[t<<4&63],o+="=="):2===n&&(t=(r[e-2]<<8)+r[e-1],o+=lookup[t>>10],o+=lookup[t>>4&63],o+=lookup[t<<2&63],o+="="),a.push(o),a.join("")}function read(r,t,e,n,o){var a,i,s=8*o-n-1,u=(1<>1,c=-7,l=e?o-1:0,p=e?-1:1,h=r[t+l];for(l+=p,a=h&(1<<-c)-1,h>>=-c,c+=s;c>0;a=256*a+r[t+l],l+=p,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+r[t+l],l+=p,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(h?-1:1);i+=Math.pow(2,n),a-=f}return(h?-1:1)*i*Math.pow(2,a-n)}function write(r,t,e,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?p/u:p*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;r[e+h]=255&s,h+=g,s/=256,o-=8);for(i=i<0;r[e+h]=255&i,h+=g,i/=256,f-=8);r[e+h-g]|=128*y}var toString$1={}.toString,isArray$1=Array.isArray||function(r){return"[object Array]"==toString$1.call(r)},INSPECT_MAX_BYTES=50;function kMaxLength(){return Buffer$2.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(r,t){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|r}function internalIsBuffer(r){return!(null==r||!r._isBuffer)}function byteLength(r,t){if(internalIsBuffer(r))return r.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer))return r.byteLength;"string"!=typeof r&&(r=""+r);var e=r.length;if(0===e)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return utf8ToBytes(r).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return base64ToBytes(r).length;default:if(n)return utf8ToBytes(r).length;t=(""+t).toLowerCase(),n=!0}}function slowToString(r,t,e){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(t>>>=0))return"";for(r||(r="utf8");;)switch(r){case"hex":return hexSlice(this,t,e);case"utf8":case"utf-8":return utf8Slice(this,t,e);case"ascii":return asciiSlice(this,t,e);case"latin1":case"binary":return latin1Slice(this,t,e);case"base64":return base64Slice(this,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,e);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}function swap(r,t,e){var n=r[t];r[t]=r[e],r[e]=n}function bidirectionalIndexOf(r,t,e,n,o){if(0===r.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=o?0:r.length-1),e<0&&(e=r.length+e),e>=r.length){if(o)return-1;e=r.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof t&&(t=Buffer$2.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(r,t,e,n,o);if("number"==typeof t)return t&=255,Buffer$2.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(r,t,e):Uint8Array.prototype.lastIndexOf.call(r,t,e):arrayIndexOf(r,[t],e,n,o);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(r,t,e,n,o){var a,i=1,s=r.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(r.length<2||t.length<2)return-1;i=2,s/=2,u/=2,e/=2}function f(r,t){return 1===i?r[t]:r.readUInt16BE(t*i)}if(o){var c=-1;for(a=e;as&&(e=s-u),a=e;a>=0;a--){for(var l=!0,p=0;po&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=e)switch(l){case 1:f<128&&(c=f);break;case 2:128==(192&(a=r[o+1]))&&(u=(31&f)<<6|63&a)>127&&(c=u);break;case 3:a=r[o+1],i=r[o+2],128==(192&a)&&128==(192&i)&&(u=(15&f)<<12|(63&a)<<6|63&i)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=r[o+1],i=r[o+2],s=r[o+3],128==(192&a)&&128==(192&i)&&128==(192&s)&&(u=(15&f)<<18|(63&a)<<12|(63&i)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,l=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=l}return decodeCodePointsArray(n)}Buffer$2.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer$2.poolSize=8192,Buffer$2._augment=function(r){return r.__proto__=Buffer$2.prototype,r},Buffer$2.from=function(r,t,e){return from(null,r,t,e)},Buffer$2.TYPED_ARRAY_SUPPORT&&(Buffer$2.prototype.__proto__=Uint8Array.prototype,Buffer$2.__proto__=Uint8Array),Buffer$2.alloc=function(r,t,e){return alloc(null,r,t,e)},Buffer$2.allocUnsafe=function(r){return allocUnsafe$1(null,r)},Buffer$2.allocUnsafeSlow=function(r){return allocUnsafe$1(null,r)},Buffer$2.isBuffer=isBuffer$1,Buffer$2.compare=function(r,t){if(!internalIsBuffer(r)||!internalIsBuffer(t))throw new TypeError("Arguments must be Buffers");if(r===t)return 0;for(var e=r.length,n=t.length,o=0,a=Math.min(e,n);o0&&(r=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(r+=" ... ")),""},Buffer$2.prototype.compare=function(r,t,e,n,o){if(!internalIsBuffer(r))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===e&&(e=r?r.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||e>r.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=e)return 0;if(n>=o)return-1;if(t>=e)return 1;if(this===r)return 0;for(var a=(o>>>=0)-(n>>>=0),i=(e>>>=0)-(t>>>=0),s=Math.min(a,i),u=this.slice(n,o),f=r.slice(t,e),c=0;co)&&(e=o),r.length>0&&(e<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return hexWrite(this,r,t,e);case"utf8":case"utf-8":return utf8Write(this,r,t,e);case"ascii":return asciiWrite(this,r,t,e);case"latin1":case"binary":return latin1Write(this,r,t,e);case"base64":return base64Write(this,r,t,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,r,t,e);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Buffer$2.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(r){var t=r.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,r);for(var e="",n=0;nn)&&(e=n);for(var o="",a=t;ae)throw new RangeError("Trying to access beyond buffer length")}function checkInt(r,t,e,n,o,a){if(!internalIsBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||tr.length)throw new RangeError("Index out of range")}function objectWriteUInt16(r,t,e,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(r.length-e,2);o>>8*(n?o:1-o)}function objectWriteUInt32(r,t,e,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(r.length-e,4);o>>8*(n?o:3-o)&255}function checkIEEE754(r,t,e,n,o,a){if(e+n>r.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function writeFloat(r,t,e,n,o){return o||checkIEEE754(r,t,e,4),write(r,t,e,n,23,4),e+4}function writeDouble(r,t,e,n,o){return o||checkIEEE754(r,t,e,8),write(r,t,e,n,52,8),e+8}Buffer$2.prototype.slice=function(r,t){var e,n=this.length;if((r=~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[r+--t]*o;return n},Buffer$2.prototype.readUInt8=function(r,t){return t||checkOffset(r,1,this.length),this[r]},Buffer$2.prototype.readUInt16LE=function(r,t){return t||checkOffset(r,2,this.length),this[r]|this[r+1]<<8},Buffer$2.prototype.readUInt16BE=function(r,t){return t||checkOffset(r,2,this.length),this[r]<<8|this[r+1]},Buffer$2.prototype.readUInt32LE=function(r,t){return t||checkOffset(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+16777216*this[r+3]},Buffer$2.prototype.readUInt32BE=function(r,t){return t||checkOffset(r,4,this.length),16777216*this[r]+(this[r+1]<<16|this[r+2]<<8|this[r+3])},Buffer$2.prototype.readIntLE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=this[r],o=1,a=0;++a=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer$2.prototype.readIntBE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=t,o=1,a=this[r+--n];n>0&&(o*=256);)a+=this[r+--n]*o;return a>=(o*=128)&&(a-=Math.pow(2,8*t)),a},Buffer$2.prototype.readInt8=function(r,t){return t||checkOffset(r,1,this.length),128&this[r]?-1*(255-this[r]+1):this[r]},Buffer$2.prototype.readInt16LE=function(r,t){t||checkOffset(r,2,this.length);var e=this[r]|this[r+1]<<8;return 32768&e?4294901760|e:e},Buffer$2.prototype.readInt16BE=function(r,t){t||checkOffset(r,2,this.length);var e=this[r+1]|this[r]<<8;return 32768&e?4294901760|e:e},Buffer$2.prototype.readInt32LE=function(r,t){return t||checkOffset(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},Buffer$2.prototype.readInt32BE=function(r,t){return t||checkOffset(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},Buffer$2.prototype.readFloatLE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!0,23,4)},Buffer$2.prototype.readFloatBE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!1,23,4)},Buffer$2.prototype.readDoubleLE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!0,52,8)},Buffer$2.prototype.readDoubleBE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!1,52,8)},Buffer$2.prototype.writeUIntLE=function(r,t,e,n){(r=+r,t|=0,e|=0,n)||checkInt(this,r,t,e,Math.pow(2,8*e)-1,0);var o=1,a=0;for(this[t]=255&r;++a=0&&(a*=256);)this[t+o]=r/a&255;return t+e},Buffer$2.prototype.writeUInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,255,0),Buffer$2.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[t]=255&r,t+1},Buffer$2.prototype.writeUInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer$2.prototype.writeUInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer$2.prototype.writeUInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t+3]=r>>>24,this[t+2]=r>>>16,this[t+1]=r>>>8,this[t]=255&r):objectWriteUInt32(this,r,t,!0),t+4},Buffer$2.prototype.writeUInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>24,this[t+1]=r>>>16,this[t+2]=r>>>8,this[t+3]=255&r):objectWriteUInt32(this,r,t,!1),t+4},Buffer$2.prototype.writeIntLE=function(r,t,e,n){if(r=+r,t|=0,!n){var o=Math.pow(2,8*e-1);checkInt(this,r,t,e,o-1,-o)}var a=0,i=1,s=0;for(this[t]=255&r;++a>0)-s&255;return t+e},Buffer$2.prototype.writeIntBE=function(r,t,e,n){if(r=+r,t|=0,!n){var o=Math.pow(2,8*e-1);checkInt(this,r,t,e,o-1,-o)}var a=e-1,i=1,s=0;for(this[t+a]=255&r;--a>=0&&(i*=256);)r<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(r/i>>0)-s&255;return t+e},Buffer$2.prototype.writeInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,127,-128),Buffer$2.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[t]=255&r,t+1},Buffer$2.prototype.writeInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer$2.prototype.writeInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer$2.prototype.writeInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8,this[t+2]=r>>>16,this[t+3]=r>>>24):objectWriteUInt32(this,r,t,!0),t+4},Buffer$2.prototype.writeInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),Buffer$2.TYPED_ARRAY_SUPPORT?(this[t]=r>>>24,this[t+1]=r>>>16,this[t+2]=r>>>8,this[t+3]=255&r):objectWriteUInt32(this,r,t,!1),t+4},Buffer$2.prototype.writeFloatLE=function(r,t,e){return writeFloat(this,r,t,!0,e)},Buffer$2.prototype.writeFloatBE=function(r,t,e){return writeFloat(this,r,t,!1,e)},Buffer$2.prototype.writeDoubleLE=function(r,t,e){return writeDouble(this,r,t,!0,e)},Buffer$2.prototype.writeDoubleBE=function(r,t,e){return writeDouble(this,r,t,!1,e)},Buffer$2.prototype.copy=function(r,t,e,n){if(e||(e=0),n||0===n||(n=this.length),t>=r.length&&(t=r.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),r.length-t=0;--o)r[o+t]=this[o+e];else if(a<1e3||!Buffer$2.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,r||(r=0),"number"==typeof r)for(a=t;a55295&&e<57344){if(!o){if(e>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=e;continue}if(e<56320){(t-=3)>-1&&a.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,e<128){if((t-=1)<0)break;a.push(e)}else if(e<2048){if((t-=2)<0)break;a.push(e>>6|192,63&e|128)}else if(e<65536){if((t-=3)<0)break;a.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return a}function asciiToBytes(r){for(var t=[],e=0;e>8,o=e%256,a.push(o),a.push(n);return a}function base64ToBytes(r){return toByteArray(base64clean(r))}function blitBuffer(r,t,e,n){for(var o=0;o=t.length||o>=r.length);++o)t[o+e]=r[o];return o}function isnan(r){return r!=r}function isBuffer$1(r){return null!=r&&(!!r._isBuffer||isFastBuffer(r)||isSlowBuffer(r))}function isFastBuffer(r){return!!r.constructor&&"function"==typeof r.constructor.isBuffer&&r.constructor.isBuffer(r)}function isSlowBuffer(r){return"function"==typeof r.readFloatLE&&"function"==typeof r.slice&&isFastBuffer(r.slice(0,0))}function buff(r,t){return void 0===t&&(t=BASE64_FORMAT),isBuffer$1(r)?r:new Buffer$2.from(r,t)}var replaceErrors=function(r,t){if(t instanceof Error){var e={};return Object.getOwnPropertyNames(t).forEach((function(r){e[r]=t[r]})),e}return t},printError=function(r){return JSON.stringify(r,replaceErrors)};function findFromContract(r,t,e){return!!(e[r]&&e[r][t]&&e[r][t].file&&fs.existsSync(e[r][t].file))&&e[r][t].file}var DOT=".",getDocLen=function(r){return Buffer$2.byteLength(r,"utf8")},headerParser=function(r,t){try{var e=r.headers.accept.split(",");return t?e.filter((function(r){return r===t})):e}catch(r){return[]}},isHeaderPresent=function(r,t){return!!headerParser(r,t).length},getPathToFn=function(r,t,e){var n=e.resolverDir,o=dasherize(r),a=[];e.contract&&e.contract[t]&&e.contract[t].path&&a.push(e.contract[t].path),a.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),a.push(path.join(n,t,[o,EXT].join(DOT)));for(var i=a.length,s=0;s e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n"],"names":["const"],"mappings":"iw4BAAAA,yrQCAA"} \ No newline at end of file +{"version":3,"file":"main.js","sources":["node_modules/jsonql-errors/src/get-error-name-by-instance.js","node_modules/buffer-es6/isArray.js"],"sourcesContent":["const UNKNOWN_ERROR = 'unknown'\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {array} filtered with name as value\n */\nfunction mapErrToName(errs, e) {\n return errs.filter(err => e instanceof err)\n .map(err => err.name)\n}\n\n/**\n * @param {array} errs list of errors to compare from\n * @param {object} e the error captured\n * @return {string} name of the error object\n */\nfunction getErrorNameByInstance(errs, e) {\n let error = mapErrToName(errs, e)\n return error.length ? error[0] : UNKNOWN_ERROR\n}\n\n/**\n * the same as above with a default JsonqlError as default\n * @param {array} errs same\n * @param {object} e error itself\n * @return {string} the name of the error\n */\nfunction getErrorNameByInstanceWithDefault(errs, e) {\n let name = getErrorNameByInstance(errs, e)\n return name === UNKNOWN_ERROR ? 'JsonqlError' : name;\n}\n\n\nexport {\n getErrorNameByInstanceWithDefault,\n getErrorNameByInstance,\n UNKNOWN_ERROR\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n"],"names":["const"],"mappings":"8y4BAAAA,yrQCAA"} \ No newline at end of file diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index 3a003716..804d5bf8 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -51,7 +51,7 @@ "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.2", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.7.5", + "jsonql-utils": "^0.7.6", "nb-event-service": "^1.8.3" }, "devDependencies": { -- Gitee From f1286411f59aedc3fff40dd3b5029578d8ab2f3f Mon Sep 17 00:00:00 2001 From: joelchu Date: Thu, 17 Oct 2019 15:12:39 +0800 Subject: [PATCH 19/24] both the onResult and the first then got the ack result --- packages/ws-client/package.json | 2 +- packages/ws-client/src/core/generator.js | 75 ++++++++++++++-------- packages/ws-client/src/utils/ee.js | 4 +- packages/ws-client/src/utils/helpers.js | 9 ++- packages/ws-client/src/utils/index.js | 6 +- packages/ws-client/tests/test-node.test.js | 59 ++++++++++++++--- 6 files changed, 117 insertions(+), 38 deletions(-) diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index 804d5bf8..7676740b 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -13,7 +13,7 @@ ], "scripts": { "test": "ava --verbose", - "test:node": "DEBUG=jsonql-ws-client* ava --verbose ./tests/test-node.test.js", + "test:node": "DEBUG=jsonql-ws-* ava --verbose ./tests/test-node.test.js", "contract": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config.js", "contract:auth": "node ./node_modules/jsonql-contract/cmd.js configFile ./tests/fixtures/contract-config-auth.js" }, diff --git a/packages/ws-client/src/core/generator.js b/packages/ws-client/src/core/generator.js index 3e7f5de6..cab21844 100644 --- a/packages/ws-client/src/core/generator.js +++ b/packages/ws-client/src/core/generator.js @@ -14,7 +14,6 @@ import { } from 'jsonql-errors' import { validateAsync, - validateSync, isKeyInObject, isString } from 'jsonql-params-validator' @@ -30,12 +29,15 @@ import { READY_PROP_NAME, LOGOUT_EVENT_NAME } from 'jsonql-constants' -import { injectToFn, objDefineProps } from 'jsonql-utils' -import { getDebug, createEvt, toArray } from '../utils' +import { getDebug, createEvt, toArray, injectToFn, objDefineProps } from '../utils' import { EMIT_EVT, NOT_ALLOW_OP, UNKNOWN_RESULT, MY_NAMESPACE } from '../options/constants' -const debugFn = getDebug('generator') +// const debugFn = getDebug('[generator]') + +import debug from 'debug' +const debugFn = debug('jsonql-ws-client:generator') + /** * prepare the methods @@ -98,28 +100,37 @@ function createResolver(ee, namespace, resolverName, params) { function actionCall(ee, namespace, resolverName, args = []) { const eventName = createEvt(namespace, EMIT_EVT) debugFn(`actionCall: ${eventName} --> ${resolverName}`, args) - ee.$trigger(eventName, [ - resolverName, - toArray(args) - ]) + ee.$trigger(eventName, [resolverName, toArray(args)]) + // once we trigger there is nothing return from the resolve + // @TODO if we need the next then call to have the result back + // then we need to listen to the event callback here as well + return new Promise((resolver, rejecter) => { + ee.$on( + createEvt(namespace, resolverName, RESULT_PROP_NAME), + result => { + debugFn(`got the first result`, result) + respondHandler(result, resolver, rejecter) + } + ) + }) } /** * break out to use in different places to handle the return from server * @param {object} data from server - * @param {function} resolver from promise - * @param {function} rejecter from promise + * @param {function} resolver NOT from promise + * @param {function} rejecter NOT from promise * @return {void} nothing */ function respondHandler(data, resolver, rejecter) { if (isKeyInObject(data, ERROR_KEY)) { - debugFn('rejecter called', data[ERROR_KEY]) + debugFn('-- rejecter called --', data[ERROR_KEY]) rejecter(data[ERROR_KEY]) } else if (isKeyInObject(data, DATA_KEY)) { - debugFn('resolver called', data[DATA_KEY]) + debugFn('-- resolver called --', data[DATA_KEY]) resolver(data[DATA_KEY]) } else { - debugFn('UNKNOWN_RESULT', data) + debugFn('-- UNKNOWN_RESULT --', data) rejecter({message: UNKNOWN_RESULT, error: data}) } } @@ -139,7 +150,7 @@ const setupResolver = (namespace, resolverName, params, fn, ee) => { // onResult handler _fn = objDefineProps(_fn, RESULT_PROP_NAME, function(resultCallback) { if (typeof resultCallback === 'function') { - ee.$only( + ee.$on( createEvt(namespace, resolverName, RESULT_PROP_NAME), function resultHandler(result) { respondHandler(result, resultCallback, (error) => { @@ -173,18 +184,30 @@ const setupResolver = (namespace, resolverName, params, fn, ee) => { }) // pairing with the server vesrion SEND_MSG_PROP_NAME _fn = objDefineProps(_fn, SEND_MSG_PROP_NAME, function(messagePayload) { - const result = validateSync(toArray(messagePayload), params.params, true) - // here is the different we don't throw erro instead we trigger an - // onError - if (result[ERROR_KEY] && result[ERROR_KEY].length) { - ee.$call( - createEvt(namespace, resolverName, ERROR_PROP_NAME), - [JsonqlValidationError(resolverName, result[ERROR_KEY])] - ) - } else { - // there is no return only an action call - actionCall(ee, namespace, resolverName, result[DATA_KEY]) - } + debugFn('got payload for', messagePayload) + // @NOTE change from sync interface to async @ 1.0.0 + // this way we will able to catch all the error(s) + validateAsync(toArray(messagePayload), params.params, true) + .then(result => { + // here is the different we don't throw error instead we trigger onError + if (result[ERROR_KEY] && result[ERROR_KEY].length) { + debugFn(`got ERROR_KEY`, result[ERROR_KEY]) + ee.$call( + createEvt(namespace, resolverName, ERROR_PROP_NAME), + [JsonqlValidationError(resolverName, result[ERROR_KEY])] + ) + } else { + // there is no return only an action call + actionCall(ee, namespace, resolverName, messagePayload) + } + }) + .catch(err => { + debugFn(`error after validateAsync`, err) + ee.$call( + createEvt(namespace, resolverName, ERROR_PROP_NAME), + [JsonqlValidationError(resolverName, err)] + ) + }) }) return _fn; } diff --git a/packages/ws-client/src/utils/ee.js b/packages/ws-client/src/utils/ee.js index dcf92620..d16626e5 100644 --- a/packages/ws-client/src/utils/ee.js +++ b/packages/ws-client/src/utils/ee.js @@ -5,7 +5,9 @@ import NBEventService from 'nb-event-service' export default class JsonqlWsEvt extends NBEventService { constructor() { - super({logger: getDebug('nb-event-service')}) + super({ + // logger: getDebug('nb-event-service') + }) } get name() { diff --git a/packages/ws-client/src/utils/helpers.js b/packages/ws-client/src/utils/helpers.js index 72f62007..b9afa2fa 100644 --- a/packages/ws-client/src/utils/helpers.js +++ b/packages/ws-client/src/utils/helpers.js @@ -40,7 +40,7 @@ export const clearMainEmitEvt = (ee, namespace) => { */ export const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => { try { - // + // @TODO need to figure out a better way here? const method = type === JS_WS_SOCKET_IO_NAME ? 'disconnect' : 'terminate'; for (let namespace in nsps) { let nsp = nsps[namespace] @@ -53,3 +53,10 @@ export const disconnect = (nsps, type = JS_WS_SOCKET_IO_NAME) => { console.error('Disconnect call failed', e) } } + +/** + * Simple check if the prop is function + * @param {*} prop input + * @return {boolean} true on success + */ +export const isFunc = prop => typeof prop === 'function'; diff --git a/packages/ws-client/src/utils/index.js b/packages/ws-client/src/utils/index.js index 0507fa6f..f6a8c74c 100644 --- a/packages/ws-client/src/utils/index.js +++ b/packages/ws-client/src/utils/index.js @@ -1,7 +1,7 @@ // export the util methods import { isArray } from 'jsonql-params-validator' // moved to jsonql-utils -import { toArray, createEvt } from 'jsonql-utils' +import { toArray, createEvt, injectToFn, objDefineProps } from 'jsonql-utils' import ee from './ee' import getDebug from './get-debug' @@ -16,8 +16,12 @@ import { // export export { isArray, + toArray, createEvt, + injectToFn, + objDefineProps, + ee, getDebug, processContract, diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index 2be75b42..15b23494 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -14,7 +14,25 @@ const wsClient = jsonqlWsClient.default const contractDir = join(__dirname, 'fixtures', 'contract', 'auth') const contract = fsx.readJsonSync(join(contractDir, 'contract.json')) const publicContract = fsx.readJsonSync(join(contractDir, 'public-contract.json')) -const { NOT_LOGIN_ERR_MSG, JS_WS_NAME } = require('jsonql-constants') + + +import { + NOT_LOGIN_ERR_MSG, + JS_WS_NAME, + + ERROR_TYPE, + DATA_KEY, + ERROR_KEY, + ERROR_PROP_NAME, + MESSAGE_PROP_NAME, + RESULT_PROP_NAME, + SEND_MSG_PROP_NAME, + LOGIN_EVENT_NAME, + READY_PROP_NAME, + LOGOUT_EVENT_NAME +} from 'jsonql-constants' + + const payload = {name: 'Joel'}; const token = genToken(payload) const port = 8010; @@ -50,21 +68,46 @@ test.serial('It should able to create the WebSocket client object', t => { }) test.serial.cb('The ws client can connect to the WebSocket server public interface', t => { - t.plan(1) - + t.plan(2) + let ctn = 0; const client = t.context.client; - client.pinging('ping') + client.pinging.onResult = function(result) { + ++ctn + debug(`${ctn} result`, result) + t.pass() + } + + client.pinging.onError = function(err) { + ++ctn; + debug(`[got error]`, err.error.detail[0]) + t.pass() + } + + client.pinging.onMessage = function(msg) { + ++ctn; + debug(`${ctn} ${MESSAGE_PROP_NAME}`, msg) + t.pass() + t.end() + } + + client.pinging('xxx') .then(msg => { + ++ctn; // @NOTE perhaps I should consider when return the // the promise, I could also return the socket object for use as well - debug(msg) + debug(`${ctn} Success`, msg) t.pass() - t.end() + // t.end() + + // client.pinging.send = 'ping' + }) .catch(err => { - debug(err) + debug('ERROR!', err) t.pass() - t.end() + // t.end() }) + + }) -- Gitee From 43b9211eda100212367e66f79e5c5e92d88a1c45 Mon Sep 17 00:00:00 2001 From: joelchu Date: Thu, 17 Oct 2019 16:51:25 +0800 Subject: [PATCH 20/24] add back the missing function for server to reply --- packages/ws-client/tests/test-node.test.js | 2 +- packages/ws-server/package.json | 2 +- packages/ws-server/src/core/add-property.js | 5 ++-- .../ws-server/src/core/create-ws-reply.js | 28 +++++++++++++++++++ 4 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 packages/ws-server/src/core/create-ws-reply.js diff --git a/packages/ws-client/tests/test-node.test.js b/packages/ws-client/tests/test-node.test.js index 15b23494..2d6cb42e 100644 --- a/packages/ws-client/tests/test-node.test.js +++ b/packages/ws-client/tests/test-node.test.js @@ -100,7 +100,7 @@ test.serial.cb('The ws client can connect to the WebSocket server public interfa t.pass() // t.end() - // client.pinging.send = 'ping' + client.pinging.send = 'ping' }) .catch(err => { diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index 56d143a9..dc56bccb 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-server", - "version": "1.3.0", + "version": "1.3.1", "description": "Setup WebSocket server for the jsonql to run on the same host, automatic generate public / private channel using contract", "main": "index.js", "files": [ diff --git a/packages/ws-server/src/core/add-property.js b/packages/ws-server/src/core/add-property.js index fbbf2d79..aaa986cb 100644 --- a/packages/ws-server/src/core/add-property.js +++ b/packages/ws-server/src/core/add-property.js @@ -1,7 +1,7 @@ // add required properties to the resolver -const createWsReply = require('./create-ws-reply') const { EMIT_REPLY_TYPE, SEND_MSG_PROP_NAME, MESSAGE_PROP_NAME } = require('jsonql-constants') - +// @BUG it's weird this file is not here but no error was throw +const { createWsReply } = require('./create-ws-reply') const { objDefineProps } = require('jsonql-utils') const { nil } = require('../share/helpers') @@ -15,6 +15,7 @@ const addProperty = (fn, resolverName, ws) => { let resolver; resolver = objDefineProps(fn, SEND_MSG_PROP_NAME, function(prop) { + // @TODO should this get validate as well? ws.send(createWsReply(EMIT_REPLY_TYPE, resolverName, prop)) }, nil) /* diff --git a/packages/ws-server/src/core/create-ws-reply.js b/packages/ws-server/src/core/create-ws-reply.js new file mode 100644 index 00000000..519b3cb8 --- /dev/null +++ b/packages/ws-server/src/core/create-ws-reply.js @@ -0,0 +1,28 @@ +// for some really really weird reason if I put this into the utils/helpers +// its unable to import into the module here +// since this is for ws only then we could just put in here instead +const { + WS_REPLY_TYPE, + WS_EVT_NAME, + WS_DATA_NAME +} = require('jsonql-constants') +// const debug = require('debug')('jsonql-ws-server:create-ws-reply'); +/** + * The ws doesn't have a acknowledge callback like socket.io + * so we have to DIY one for ws and other that doesn't have it + * @param {string} type of reply + * @param {string} resolverName which is replying + * @param {*} data payload + * @return {string} stringify json + */ +const createWsReply = (type, resolverName, data) => { + return JSON.stringify({ + data: { + [WS_REPLY_TYPE]: type, + [WS_EVT_NAME]: resolverName, + [WS_DATA_NAME]: data + } + }) +} + +module.exports = { createWsReply } -- Gitee From e909a1bf49d9e9d6ebccba36af545e0a32c68d79 Mon Sep 17 00:00:00 2001 From: joelchu Date: Thu, 17 Oct 2019 17:21:50 +0800 Subject: [PATCH 21/24] add debug to check if the send got the correct params --- packages/ws-server/src/core/add-property.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ws-server/src/core/add-property.js b/packages/ws-server/src/core/add-property.js index aaa986cb..f77884ec 100644 --- a/packages/ws-server/src/core/add-property.js +++ b/packages/ws-server/src/core/add-property.js @@ -1,10 +1,10 @@ // add required properties to the resolver const { EMIT_REPLY_TYPE, SEND_MSG_PROP_NAME, MESSAGE_PROP_NAME } = require('jsonql-constants') // @BUG it's weird this file is not here but no error was throw -const { createWsReply } = require('./create-ws-reply') -const { objDefineProps } = require('jsonql-utils') -const { nil } = require('../share/helpers') +const { objDefineProps } = require('jsonql-utils') +const { nil, createWsReply, getDebug } = require('../share/helpers') +const debug = getDebug(`addProperty`) /** * @param {function} fn the actual resolver function * @param {string} resolverName name of resolver @@ -13,7 +13,7 @@ const { nil } = require('../share/helpers') */ const addProperty = (fn, resolverName, ws) => { let resolver; - + debug(`add ${SEND_MSG_PROP_NAME} to ${resolverName}`) resolver = objDefineProps(fn, SEND_MSG_PROP_NAME, function(prop) { // @TODO should this get validate as well? ws.send(createWsReply(EMIT_REPLY_TYPE, resolverName, prop)) -- Gitee From 3b548b90d12f9bd12fcd55f9217749c3cda39b1e Mon Sep 17 00:00:00 2001 From: joelchu Date: Thu, 17 Oct 2019 17:23:28 +0800 Subject: [PATCH 22/24] jsonql-ws-server to 1.3.1 --- packages/ws-client/package.json | 2 +- packages/ws-server/package.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ws-client/package.json b/packages/ws-client/package.json index 7676740b..4cbd65e8 100755 --- a/packages/ws-client/package.json +++ b/packages/ws-client/package.json @@ -59,7 +59,7 @@ "esm": "^3.2.25", "fs-extra": "^8.1.0", "jsonql-contract": "^1.7.21", - "jsonql-ws-server": "^1.3.0", + "jsonql-ws-server": "^1.3.1", "kefir": "^3.8.6", "ws": "^7.1.2" }, diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index dc56bccb..61f85a81 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -31,19 +31,19 @@ "debug": "^4.1.1", "esm": "^3.2.25", "fs-extra": "^8.1.0", - "jsonql-constants": "^1.8.3", + "jsonql-constants": "^1.8.4", "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.2", "jsonql-params-validator": "^1.4.11", "jsonql-resolver": "^0.9.4", - "jsonql-utils": "^0.7.4", + "jsonql-utils": "^0.7.6", "lodash": "^4.17.15", "ws": "^7.1.2" }, "devDependencies": { "ava": "^2.4.0", "jsonql-contract": "^1.7.21", - "open": "^6.4.0" + "open": "^7.0.0" }, "ava": { "files": [ -- Gitee From ba3ebee2513ebc613a936b7dc8e33dc934a9b151 Mon Sep 17 00:00:00 2001 From: joelchu Date: Thu, 17 Oct 2019 17:28:16 +0800 Subject: [PATCH 23/24] The debug is not showing anything inside the resolver --- .../tests/fixtures/resolvers/socket/public/pinging.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js b/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js index 82160f2a..739bac32 100644 --- a/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js +++ b/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js @@ -11,14 +11,16 @@ module.exports = function pinging(msg) { if (ctn > 0) { switch (msg) { case 'ping': + debug(`got a ping`) pinging.send = 'pong'; case 'pong': + debug(`got a pong`) pinging.send = 'ping'; default: return `Got your message ${msg}`; //pinging.send = 'You lose!'; } - return; + return true; } ++ctn; debug(`Did return here`) -- Gitee From e61b67e434345a13241914f8a0908b2bc3f30d59 Mon Sep 17 00:00:00 2001 From: joelchu Date: Thu, 17 Oct 2019 23:03:16 +0800 Subject: [PATCH 24/24] jsonql-constants to v1.8.5 add USERDATA_PROP_NAME --- packages/constants/README.md | 1 + packages/constants/constants.json | 1 + packages/constants/main.js | 1 + packages/constants/module.js | 1 + packages/constants/package.json | 2 +- packages/ws-client/src/core/generator.js | 2 +- .../fixtures/beta/src/ws/ws-main-handler.js | 3 +- .../resolvers/socket/public/pinging.js | 2 +- packages/ws-server/package.json | 2 +- packages/ws-server/src/core/add-property.js | 33 ------------- .../ws-server/src/core/create-ws-reply.js | 28 ----------- packages/ws-server/src/share/add-property.js | 48 +++++++++++++++++++ packages/ws-server/src/share/helpers.js | 2 - .../ws-server/src/share/resolve-method.js | 14 +----- 14 files changed, 59 insertions(+), 81 deletions(-) delete mode 100644 packages/ws-server/src/core/add-property.js delete mode 100644 packages/ws-server/src/core/create-ws-reply.js create mode 100644 packages/ws-server/src/share/add-property.js diff --git a/packages/constants/README.md b/packages/constants/README.md index 78beb4db..a057240a 100755 --- a/packages/constants/README.md +++ b/packages/constants/README.md @@ -109,6 +109,7 @@ non-javascript to develop your tool. You can also use the included `constants.js - READY_PROP_NAME - SEND_MSG_PROP_NAME - CLIENT_PROP_NAME +- USERDATA_PROP_NAME - DEFAULT_WS_WAIT_TIME - TIMEOUT_ERR_MSG - NOT_LOGIN_ERR_MSG diff --git a/packages/constants/constants.json b/packages/constants/constants.json index f82ac190..0b7ec2cc 100644 --- a/packages/constants/constants.json +++ b/packages/constants/constants.json @@ -141,6 +141,7 @@ "READY_PROP_NAME": "onReady", "SEND_MSG_PROP_NAME": "send", "CLIENT_PROP_NAME": "client", + "USERDATA_PROP_NAME": "userdata", "DEFAULT_WS_WAIT_TIME": 5000, "TIMEOUT_ERR_MSG": "timeout", "NOT_LOGIN_ERR_MSG": "NOT LOGIN", diff --git a/packages/constants/main.js b/packages/constants/main.js index bc497f1b..80870bf6 100644 --- a/packages/constants/main.js +++ b/packages/constants/main.js @@ -141,6 +141,7 @@ module.exports = { "READY_PROP_NAME": "onReady", "SEND_MSG_PROP_NAME": "send", "CLIENT_PROP_NAME": "client", + "USERDATA_PROP_NAME": "userdata", "DEFAULT_WS_WAIT_TIME": 5000, "TIMEOUT_ERR_MSG": "timeout", "NOT_LOGIN_ERR_MSG": "NOT LOGIN", diff --git a/packages/constants/module.js b/packages/constants/module.js index f56525f8..eec341bc 100644 --- a/packages/constants/module.js +++ b/packages/constants/module.js @@ -147,6 +147,7 @@ export const READY_PROP_NAME = 'onReady'; export const SEND_MSG_PROP_NAME = 'send'; // this one is for nodeClient inject into the resolver export const CLIENT_PROP_NAME = 'client'; +export const USERDATA_PROP_NAME = 'userdata'; // this is the default time to wait for reply if exceed this then we // trigger an error --> 5 seconds diff --git a/packages/constants/package.json b/packages/constants/package.json index 234eae0c..97722c90 100755 --- a/packages/constants/package.json +++ b/packages/constants/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-constants", - "version": "1.8.4", + "version": "1.8.5", "description": "All the share constants for json:ql tools", "main": "main.js", "module": "module.js", diff --git a/packages/ws-client/src/core/generator.js b/packages/ws-client/src/core/generator.js index cab21844..3ceb0dda 100644 --- a/packages/ws-client/src/core/generator.js +++ b/packages/ws-client/src/core/generator.js @@ -84,7 +84,7 @@ function createResolver(ee, namespace, resolverName, params) { // note we pass the new withResult=true option return function(...args) { return validateAsync(args, params.params, true) - .then( _args => actionCall(ee, namespace, resolverName, _args) ) + .then(_args => actionCall(ee, namespace, resolverName, _args)) .catch(finalCatch) } } diff --git a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js index 42c16a38..b52d32b0 100644 --- a/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js +++ b/packages/ws-client/tests/fixtures/beta/src/ws/ws-main-handler.js @@ -53,7 +53,7 @@ const errorTypeHandler = (ee, namespace, resolverName, json) => { export default function wsMainHandlerAction(namespace, ws, ee) { // send ws.onopen = function() { - debugFn('onopen listened') + debugFn('ws.onopen listened') // we just call the onReady ee.$call(READY_PROP_NAME, namespace) // add listener @@ -98,6 +98,7 @@ export default function wsMainHandlerAction(namespace, ws, ee) { // ee.$trigger(createEvt(namespace, resolverName, RESULT_PROP_NAME), [error]) } } catch(e) { + debug(`ws.onmessage error`, e) errorTypeHandler(ee, namespace, false, e) } } diff --git a/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js b/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js index 739bac32..9aa000f3 100644 --- a/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js +++ b/packages/ws-client/tests/fixtures/resolvers/socket/public/pinging.js @@ -7,7 +7,7 @@ let ctn = 0; * @return {string} reply message based on your message */ module.exports = function pinging(msg) { - debug(`got call with --> ${msg}`) + debug(`--> got call with --> ${msg}`) if (ctn > 0) { switch (msg) { case 'ping': diff --git a/packages/ws-server/package.json b/packages/ws-server/package.json index 61f85a81..eb561831 100755 --- a/packages/ws-server/package.json +++ b/packages/ws-server/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-ws-server", - "version": "1.3.1", + "version": "1.3.2", "description": "Setup WebSocket server for the jsonql to run on the same host, automatic generate public / private channel using contract", "main": "index.js", "files": [ diff --git a/packages/ws-server/src/core/add-property.js b/packages/ws-server/src/core/add-property.js deleted file mode 100644 index f77884ec..00000000 --- a/packages/ws-server/src/core/add-property.js +++ /dev/null @@ -1,33 +0,0 @@ -// add required properties to the resolver -const { EMIT_REPLY_TYPE, SEND_MSG_PROP_NAME, MESSAGE_PROP_NAME } = require('jsonql-constants') -// @BUG it's weird this file is not here but no error was throw - -const { objDefineProps } = require('jsonql-utils') -const { nil, createWsReply, getDebug } = require('../share/helpers') -const debug = getDebug(`addProperty`) -/** - * @param {function} fn the actual resolver function - * @param {string} resolverName name of resolver - * @param {object} ws the io instance - * @return {function} fn with additional property - */ -const addProperty = (fn, resolverName, ws) => { - let resolver; - debug(`add ${SEND_MSG_PROP_NAME} to ${resolverName}`) - resolver = objDefineProps(fn, SEND_MSG_PROP_NAME, function(prop) { - // @TODO should this get validate as well? - ws.send(createWsReply(EMIT_REPLY_TYPE, resolverName, prop)) - }, nil) - /* - @TODO is this necessary? - resolver = addHandlerProperty(resolver, MESSAGE_PROP_NAME, function(handler) { - if (handler && typeof handler === 'function') { - - } - throw new JsonqlError(resolverName, {message: `Require ${MESSAGE_PROP_NAME} to be a function!`}) - }, nil) - */ - return resolver; -} - -module.exports = addProperty diff --git a/packages/ws-server/src/core/create-ws-reply.js b/packages/ws-server/src/core/create-ws-reply.js deleted file mode 100644 index 519b3cb8..00000000 --- a/packages/ws-server/src/core/create-ws-reply.js +++ /dev/null @@ -1,28 +0,0 @@ -// for some really really weird reason if I put this into the utils/helpers -// its unable to import into the module here -// since this is for ws only then we could just put in here instead -const { - WS_REPLY_TYPE, - WS_EVT_NAME, - WS_DATA_NAME -} = require('jsonql-constants') -// const debug = require('debug')('jsonql-ws-server:create-ws-reply'); -/** - * The ws doesn't have a acknowledge callback like socket.io - * so we have to DIY one for ws and other that doesn't have it - * @param {string} type of reply - * @param {string} resolverName which is replying - * @param {*} data payload - * @return {string} stringify json - */ -const createWsReply = (type, resolverName, data) => { - return JSON.stringify({ - data: { - [WS_REPLY_TYPE]: type, - [WS_EVT_NAME]: resolverName, - [WS_DATA_NAME]: data - } - }) -} - -module.exports = { createWsReply } diff --git a/packages/ws-server/src/share/add-property.js b/packages/ws-server/src/share/add-property.js new file mode 100644 index 00000000..9b10820f --- /dev/null +++ b/packages/ws-server/src/share/add-property.js @@ -0,0 +1,48 @@ +// add required properties to the resolver +const { + EMIT_REPLY_TYPE, + SEND_MSG_PROP_NAME, + MESSAGE_PROP_NAME, + JS_WS_NAME +} = require('jsonql-constants') +const _ = require('lodash') +// @BUG it's weird this file is not here but no error was throw +const { objDefineProps } = require('jsonql-utils') +const { nil, createWsReply, getDebug } = require('../share/helpers') +const debug = getDebug(`addProperty`) + +/* +@TODO is this necessary? +resolver = addHandlerProperty(resolver, MESSAGE_PROP_NAME, function(handler) { + if (handler && typeof handler === 'function') { + + } + throw new JsonqlError(resolverName, {message: `Require ${MESSAGE_PROP_NAME} to be a function!`}) +}, nil) +*/ + +/** + * using the serverType to provide different addProperty method to this + * @param {function} fn the resolver function + * @param {string} resolverName resolver name + * @param {object} ws the different context object + * @param {object|boolean} userdata false when there is none + * @return {function} the applied function + */ +const addProperty = (fn, resolverName, ws, userdata) => { + return _(injectToFn(fn, JS_WS_NAME, ws)) + .chain() + .thru(resolver => { + debug(`add ${SEND_MSG_PROP_NAME} to ${resolverName}`) + return objDefineProps(fn, SEND_MSG_PROP_NAME, function(prop) { + // @TODO should this get validate as well? + ws.send(createWsReply(EMIT_REPLY_TYPE, resolverName, prop)) + }, nil) + }) + .thru(resolver => { + return userdata ? provideUserdata(resolver, userdata) : resolver; + }) + .value() +} + +module.exports = { addProperty } diff --git a/packages/ws-server/src/share/helpers.js b/packages/ws-server/src/share/helpers.js index 6c2be255..ada86cfb 100644 --- a/packages/ws-server/src/share/helpers.js +++ b/packages/ws-server/src/share/helpers.js @@ -26,8 +26,6 @@ const WS_KEYS = [ WS_REPLY_TYPE, WS_EVT_NAME, WS_DATA_NAME ] const { merge } = require('lodash') - - /** * The ws doesn't have a acknowledge callback like socket.io * so we have to DIY one for ws and other that doesn't have it diff --git a/packages/ws-server/src/share/resolve-method.js b/packages/ws-server/src/share/resolve-method.js index e4686315..cd3dfdfa 100644 --- a/packages/ws-server/src/share/resolve-method.js +++ b/packages/ws-server/src/share/resolve-method.js @@ -23,19 +23,7 @@ const debug = require('debug')('jsonql-ws-server:resolve-method') const { getResolver } = require('jsonql-resolver') -/** - * using the serverType to provide different addProperty method to this - * @param {function} fn the resolver function - * @param {string} resolverName resolver name - * @param {object} ws the different context object - * @param {object|boolean} userdata false when there is none - * @return {function} the applied function - */ -const addProperty = (fn, resolverName, ws, userdata) => { - let _fn = injectToFn(fn, resolverName, ws) - // group the provide userdata together - return isUndefined(userdata) ? _fn : provideUserdata(_fn, userdata) -} +const { addProperty } = require('./add-property') /** * similiar to the one in Koa-middleware without the ctx -- Gitee