diff --git a/packages/contract-cli/README.md b/packages/contract-cli/README.md index 3294e2ef3c4c39b0d590130b39fc7aba02e6a384..2a38d0efba6fa6a9d052e19c04a01a6b30ec7282 100755 --- a/packages/contract-cli/README.md +++ b/packages/contract-cli/README.md @@ -67,7 +67,7 @@ $ jsonql-contract config ./config.json ## Supported JS -At the moment, we only support common js (`cjs`) style function exports: +We only support common js (`cjs`) style function exports and ES6 import / export style (you need to pass the `jsType: ES` when you pass configuration options to the contract generator api) ```js /** @@ -77,12 +77,27 @@ At the moment, we only support common js (`cjs`) style function exports: * @param {number} [param3=100] optional with default value of 100 * @return {number} sum of all */ -module.exports = function(param1, params2, param3=100) { +module.exports = function someResolver(param1, params2, param3=100) { return param1 + param2 + param3; } ``` -We are working on the ES2016 `es` and Typescript `ts` port at the moment. +ES6 style: + +```js +/** + * This is a query and we REQUIRED to write correct jsdoc since v1.2.x + * @param {number} param1 + * @param {number} param2 + * @param {number} [param3=100] optional with default value of 100 + * @return {number} sum of all + */ +export default function someResolver(param1, param2, param3 = 100) { + return param1 + param2 + param3 +} + +``` + ## Resolvers folder structure @@ -115,8 +130,10 @@ module.exports = async function(name, pos, options = {}) { } ``` -Your function can be an async methods, which is actually recommended. -Because when we execute your code it will look (not exactly the same) the following +Its recommended to use an `async` method as your resolver. Inside, you can return promise or use `async` `await`. + +Because when we execute your code it will look (not exactly the same) the following: + ```js ctx.body = await processResult(opts); @@ -132,11 +149,12 @@ For mutation, there will only be 2 parameters `payload` and `condition` * @param {object} condition * @return {boolean} true on success */ -module.exports = function(payload, condition) {} +module.exports = function(payload, condition) { + // do your thing +} ``` -To properly documented your mutation code for the client side validation, you should -do the following comment: +To properly documented your mutation code for the client side validation, you should do the following comment: ```js /** @@ -147,7 +165,9 @@ do the following comment: * @param {number} condition.id to id the field * @return {boolean} true on success */ -module.exports = function(payload, condition) {} +module.exports = function({ name }, { id }) { + // do something with your data +} ``` @@ -215,14 +235,10 @@ We will take the jsdoc output and create an additional temporary contract file ( - Update README about the `public` folder within each resolvers - ~~Add watch mode during development~~ - this is not activate until the other part is ready - ~~Add accept config file for easier to run in command line~~ +- add `Auth` part +- add `Socket` part +- add `File` part (not in the code base yet) --- MIT (c) [to1source](https://to1source.cn) & [NEWBRAN LTD](https://newbran.ch) - - -"socket.io-client": "^2.2.0", -"ts-node": "^8.3.0", -"typescript": "^3.5.3", -"ws": "^7.1.2", -"@types/node": "^12.7.1", diff --git a/packages/contract-cli/package.json b/packages/contract-cli/package.json index 0f87579e8b455d107c96cfca7c64d69b900c88c6..9547cf9512dd43220ca1bb2d003f10f6d6ac3fe2 100755 --- a/packages/contract-cli/package.json +++ b/packages/contract-cli/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-contract", - "version": "1.7.15", + "version": "1.7.16", "description": "JS API / command line tool to generate the contract.json for jsonql", "main": "index.js", "files": [ @@ -25,7 +25,8 @@ "test:watch": "DEBUG=jsonql-contract:* ava tests/watch.test.js", "test:config": "DEBUG=jsonql-contract:* ava tests/config-params.test.js", "test:custom": "DEBUG=jsonql-contract:* ava tests/custom-login.test.js", - "test:debug": "DEBUG=jsonql-contract* ava tests/koa-debug.test.js" + "test:debug": "DEBUG=jsonql* ava tests/koa-debug.test.js", + "test:split": "DEBUG=jsonql-contract* ava tests/split-task.test.js" }, "keywords": [ "jsonql", @@ -41,17 +42,17 @@ "jsonql-contract": "./cli.js" }, "dependencies": { - "acorn": "^7.0.0", + "acorn": "^7.1.0", "debug": "^4.1.1", "chokidar": "^3.1.1", - "colors": "^1.3.3", + "colors": "^1.4.0", "fs-extra": "^8.1.0", "glob": "^7.1.4", "jsdoc-api": "^5.0.3", "jsonql-constants": "^1.8.3", "jsonql-errors": "^1.1.3", "jsonql-params-validator": "^1.4.11", - "jsonql-utils": "^0.6.10", + "jsonql-utils": "^0.6.12", "kefir": "^3.8.6", "lodash": "^4.17.15", "yargs": "^14.0.0" diff --git a/packages/contract-cli/src/ast/jsdoc.js b/packages/contract-cli/src/ast/jsdoc.js index 3e6beee43239315c96fb2db92b3e983192cb3892..aa9a2878b30b54921c09e46d16dc96c29824a5cc 100644 --- a/packages/contract-cli/src/ast/jsdoc.js +++ b/packages/contract-cli/src/ast/jsdoc.js @@ -181,7 +181,7 @@ const searchForParams = function(output) { // debug('searchForParams', result) if (result.name && !result.params) { debug(`params is no defined?`, detailOut(result)) - debug(detailOut(output)) + debug(`output`, detailOut(output)) return search(output, result.name) } return result; diff --git a/packages/contract-cli/src/generator/es-extra.js b/packages/contract-cli/src/generator/es-post-process.js similarity index 96% rename from packages/contract-cli/src/generator/es-extra.js rename to packages/contract-cli/src/generator/es-post-process.js index 9aa343559482aaefd3eb61462912132ffea471f4..4cf10b42ca5a2046ba269df41b38c5a6f8a22e6f 100644 --- a/packages/contract-cli/src/generator/es-extra.js +++ b/packages/contract-cli/src/generator/es-post-process.js @@ -86,7 +86,7 @@ const createResolverListFile = (contract, resolverDir) => { * @param {string} resolverDir where to put the files * @return {void} nothing */ -module.exports = function postProcess(sourceType, resolverDir, contract) { +function esPostProcess(sourceType, resolverDir, contract) { debug('postProcess: sourceType:', sourceType, resolverDir) if (sourceType === MODULE_TYPE) { let src = join(__dirname , IMPORT_JS_TEMPLATE) @@ -100,3 +100,5 @@ module.exports = function postProcess(sourceType, resolverDir, contract) { } return Promise.resolve(true) } + +module.exports = { esPostProcess } diff --git a/packages/contract-cli/src/generator/files-op.js b/packages/contract-cli/src/generator/files-op.js new file mode 100644 index 0000000000000000000000000000000000000000..bbb9c95fe15a7481bf795783b5065f942a927d23 --- /dev/null +++ b/packages/contract-cli/src/generator/files-op.js @@ -0,0 +1,69 @@ +// all the files related methods +const { join } = require('path') +const fsx = require('fs-extra') + +const { isContract } = require('./helpers') +const { getDebug } = require('../utils') +const debug = getDebug('generator:files') + +/** + * Just output the final contract to json file + * @param {string} dist where it should be written + * @param {object} contract the json to write + * @return {promise} resolve the contract + */ +function writeFileOut(dist, contract) { + return new Promise((resolver, rejecter) => { + fsx.outputJson(dist, contract, {spaces: 2}, err => { + if (err) { + return rejecter(err) + } + resolver(contract) + }) + }) +} + +/** + * @param {object} config pass by the init call + * @param {string} dist where the contract file is + * @return {promise} resolve or reject if remove files failed + */ +const keepOrCleanContract = function(config, dist) { + return new Promise((resolver, rejecter) => { + if (config.alwaysNew === true) { + if (fsx.existsSync(dist)) { + debug('[@TODO] Found existing contract [%s]', dist) + fsx.remove(dist, err => { + if (err) { + return rejecter(err) + } + return resolver(true) + }) + } + } + resolver(true) + }) +} + +/** + * check if there is already a contract.json file generated + * @param {object} config options + * @return {mixed} false on fail + */ +const isContractExisted = function(config) { + const { contractDir, outputFilename } = config; + const dist = join(contractDir, outputFilename) + if (fsx.existsSync(dist)) { + debug('[isContractExisted] found') + const contract = fsx.readJsonSync(dist) + return isContract(contract) ? contract : false; + } + return false; +} + +// export +module.exports = { + keepOrCleanContract, + isContractExisted, + writeFileOut +} diff --git a/packages/contract-cli/src/generator/files.js b/packages/contract-cli/src/generator/files.js deleted file mode 100644 index fb11c1981dec327a98c8cbad3d23578fe7f0c75e..0000000000000000000000000000000000000000 --- a/packages/contract-cli/src/generator/files.js +++ /dev/null @@ -1,192 +0,0 @@ -// all the files related methods -const { inspect } = require('util') -const { join, basename } = require('path') -const fsx = require('fs-extra') -const glob = require('glob') -const colors = require('colors/safe') -const { merge } = require('lodash') -// our modules -const { RETURN_AS_JSON, MODULE_TYPE, SCRIPT_TYPE } = require('jsonql-constants') -const getResolver = require('./get-resolver') -const { - extractExtraProps, - mutateContract, - logToFile, - isContract -} = require('./helpers') -const { - astParser, - extractReturns, - extractParams, - isExpression -} = require('../ast') -const { getTimestamp, getDebug } = require('../utils') -const postProcess = require('./es-extra') -const debug = getDebug('generator:files') -// this was lost when using as api using let -let sourceType; - -/** - * Use the first file to determine the source type NOT ALLOW MIX AND MATCH - * @param {string} source the source file - * @return {string} sourceType - */ -const sourceFileType = source => { - if (sourceType) { - return sourceType; - } - if (source.indexOf('module.exports') > -1) { - sourceType = SCRIPT_TYPE - } else if (source.indexOf('export default')) { - sourceType = MODULE_TYPE - } - if (sourceType) { - // debug(`parsing ${sourceType}`) - return sourceType; - } - throw new Error(`Can not determine the source file type!`) -} - -/** - * process the files - * @param {string} inDir base directory - * @param {string} fileType the ext - * @param {array} files list of files - * @param {object} config to control the inner working - * @return {object} promise that resolve all the files key query / mutation - */ -const processFiles = function(inDir, fileType, files, config) { - let _sourceType; - const fn = getResolver(inDir, fileType, config) - return files.map( fn ) - .filter(obj => obj.ok) - .map(obj => { - const { type, name, file, public, namespace } = obj; - const source = fsx.readFileSync(file, 'utf8').toString() - // we need to automatically detect if this is a module files or script - _sourceType = sourceFileType(source) - const astOpt = { sourceType: _sourceType } - // parsing the file - const result = astParser(source, astOpt) - - logToFile(config.logDirectory, [type, name].join('-'), result) - - const baseParams = result.body.filter(isExpression).map(extractParams).filter(p => p) - const { description, params, returns } = extractExtraProps(config, result, source, name) - // return - return { - [type]: { - [name]: { - namespace, - public, // mark if this is a public accessible method or not - file, - description, - params: merge([], baseParams[0], params), // merge array NOT OBJECT - returns: returns // merge({}, takeDownArray(returns), returns) - } - } - }; - }) - .reduce(merge, { - query: {}, - mutation: {}, - auth: {}, - timestamp: getTimestamp(), - sourceType: _sourceType - }) -} - -/** - * get list of files and put them in query / mutation - * @param {string} inDir diretory - * @param {object} config pass config to the underlying method - * @param {mixed} fileType we might do a ts in the future - * @return {object} query / mutation - */ -const readFilesOutContract = function(inDir, config, fileType) { - return new Promise((resolver, rejecter) => { - glob(join(inDir, '**', ['*', fileType].join('.')), (err, files) => { - if (err) { - return rejecter(err) - } - resolver( - processFiles(inDir, fileType, files, config) - ) - }) - }) -} - -/** - * @param {object} config pass by the init call - * @param {string} dist where the contract file is - * @return {void} nothing to return - */ -const keepOrCleanContract = function(config, dist) { - // @TODO we might want to keep the file based on the configuration - if (fsx.existsSync(dist) && config.alwaysNew === true) { - debug('[@TODO] Found existing contract [%s]', dist) - return fsx.removeSync(dist) - } -} - -/** - * check if there is already a contract.json file generated - * @param {object} config options - * @return {mixed} false on fail - */ -const isContractExisted = function(config) { - const { contractDir, outputFilename } = config; - const dist = join(contractDir, outputFilename) - if (fsx.existsSync(dist)) { - debug('[isContractExisted] found') - const contract = fsx.readJsonSync(dist) - return isContract(contract) ? contract : false; - } - return false; -} - -/** - * Generate the final contract output to file - * @param {object} config output directory - * @param {object} contract processed result - * @param {boolean|object} [rawData=false] the raw contract data for ES6 create files - * @return {boolean} true on success - */ -const generateOutput = function(config, contract, rawData = false) { - // this return a promise interface - return new Promise((resolver, rejecter) => { - const { outputFilename, contractDir, resolverDir } = config; - - const dist = join(contractDir, outputFilename) - // keep or remove the existing contract file - keepOrCleanContract(config, dist) - - const finalContract = mutateContract(config, contract) - - if (!finalContract) { - throw new Error('[generateOutput] finalContract is empty?') - } - // now write out the file - fsx.outputJson(dist, finalContract, {spaces: 2}, err => { - if (err) { - return rejecter(err) - } - // new for ES6 Module - postProcess(sourceType, resolverDir, rawData || finalContract) - .then(() => { - // reset the sourceType - sourceType = undefined; - // output - resolver( - config.returnAs === RETURN_AS_JSON ? finalContract : dist - ) - }) - }) - }) -} -// export -module.exports = { - generateOutput, - readFilesOutContract, - isContractExisted -} diff --git a/packages/contract-cli/src/generator/generate-output.js b/packages/contract-cli/src/generator/generate-output.js new file mode 100644 index 0000000000000000000000000000000000000000..bb29a9b4ad12065ebbfe0be628afeef16191a56d --- /dev/null +++ b/packages/contract-cli/src/generator/generate-output.js @@ -0,0 +1,31 @@ +// the final step to generate output +const { RETURN_AS_JSON } = require('jsonql-constants') +const { keepOrCleanContract, isContractExisted, writeFileOut } = require('./files-op') +const { esPostProcess } = require('./es-post-process') +const { mutateContract } = require('./helpers') +const { join } = require('path') +/** + * Generate the final contract output to file + * @param {string} sourceType what type of file we are dealing with + * @param {object} config output directory + * @param {object} contract processed result + * @param {boolean|object} [rawData=false] the raw contract data for ES6 create files + * @return {boolean} true on success + */ +const generateOutput = function(sourceType, config, contract, rawData = false) { + // this return a promise interface + const { outputFilename, contractDir, resolverDir } = config; + const dist = join(contractDir, outputFilename) + // keep or remove the existing contract file + return keepOrCleanContract(config, dist) + .then(() => mutateContract(config, contract)) + .then(finalContract => ( + writeFileOut(dist, finalContract) + .then(contract => ( + esPostProcess(sourceType, resolverDir, rawData || contract) + .then(() => config.returnAs === RETURN_AS_JSON ? finalContract : dist) + )) + )) +} + +module.exports = { generateOutput } diff --git a/packages/contract-cli/src/generator/get-resolver.js b/packages/contract-cli/src/generator/get-resolver.js index 7a4765572459e85c51b4418dd1926e12ed71502c..ed0235d2bf189b6724201bee83a8069a5bb5cfe9 100644 --- a/packages/contract-cli/src/generator/get-resolver.js +++ b/packages/contract-cli/src/generator/get-resolver.js @@ -1,8 +1,14 @@ // this is the HEART of this module +const fsx = require('fs-extra') const { join, basename } = require('path') -const { compact } = require('lodash') -const { INDEX_KEY } = require('jsonql-constants') +const { compact, merge } = require('lodash') const { + MODULE_TYPE, + SCRIPT_TYPE, + INDEX_KEY +} = require('jsonql-constants') +const { + logToFile, inTypesArray, isAuthType, checkIfIsPublic, @@ -10,15 +16,109 @@ const { addPublicKey, packOutput } = require('./helpers') -const { getDebug } = require('../utils') +const { + astParser, + extractReturns, + extractParams, + isExpression, + getJsdoc +} = require('../ast') +const { getDebug, getTimestamp } = require('../utils') const debug = getDebug('generator:get-resolvers') +/** + * There is a potential bug here if the first file is not a resolver than this will failed! + * Use the first file to determine the source type NOT ALLOW MIX AND MATCH + * @param {string} source the path to the file + * @return {string} sourceType + */ +const sourceFileType = src => { + const source = fsx.readFileSync(src, 'utf8').toString() + if (source.indexOf('module.exports') > -1) { + return SCRIPT_TYPE + } else if (source.indexOf('export default') > -1) { + return MODULE_TYPE + } + return false; +} /** - * breaking out the getResolver, this one will able to get normal or when - * the enableAuth enable to search for files - * + * try to find out the resourceType until we find it + * @param {array} objs array of objs + * @return {object} add the resourceType to the object */ +function getSourceType(objs) { + let sourceType; + let ctn = objs.length; + for (let i = 0; i < ctn; ++i) { + if (!sourceType) { + resourceType = sourceFileType(objs[i].file) + if (resourceType) { + return resourceType + } + } + } + throw new Error(`Can not determine the resourceType!`) +} + +/** + * Breaking out from the getResolver because we need to hook another method into it + * @param {string} baseFile the path to the found file + * @param {string} inDir the base path + * @param {string} fileType ext + * @param {object} config options to use + * @return {object} with {ok:true} to id that is a resolver + */ +const checkResolver = (indexFile, inDir, fileType, config) => (baseFile) => { + const failed = {ok: false}; + const fileParts = compact(baseFile.replace(inDir, '').toLowerCase().split('/')) + const ctn = fileParts.length; + const type = fileParts[0]; + // we ignore all the fileParts on the root level + if (fileParts.length === 1) { + return failed; + } + const ext = '.' + fileType; + // process fileParts within the folder of query, mutation, auth + const fileName = basename(fileParts[1], ext) + // const evt = basename(fileParts[1]); + switch (ctn) { + case 4: // this will definely inside the public folder + if (inTypesArray(type)) { + // we need to shift down one level to get the filename + const fileName4 = basename(fileParts[2], ext) + let ok = (fileParts[ctn - 1] === indexFile) + if (checkIfIsPublic(fileParts, config)) { + // debug(4, _fileName, fileParts); + return packOutput(type, fileName4, ok, baseFile, true, config) + } else if (checkIfIsPrivate(fileParts, config)) { + return packOutput(type, fileName4, ok, baseFile, false, config) + } + } + // make sure it always terminate here + return failed; + case 3: // this could be inside the public folder + if (inTypesArray(type) || isAuthType(type, fileName, config)) { + let isPublic = checkIfIsPublic(fileParts, config) + let isPrivate = checkIfIsPrivate(fileParts, config) + let lastFile = fileParts[ctn - 1]; + let ok = lastFile === indexFile; + let fileName3 = fileName; + if (isPublic || isPrivate) { + ok = true; + fileName3 = lastFile.replace(ext, '') + } + return packOutput(type, fileName3, ok, baseFile, isPublic, config) + } + case 2: + if (inTypesArray(type) || isAuthType(type, fileName, config)) { + // debug(2, type, fileName, fileParts); + return packOutput(type, fileName, true, baseFile, false, config) + } + default: + return failed; + } +} /** * filter to get which is resolver or not @@ -27,59 +127,67 @@ const debug = getDebug('generator:get-resolvers') * @param {object} config options to use * @return {function} work out if it's or not */ -const getResolver = function(inDir, fileType, config) { +function getResolver(inDir, fileType, config) { const indexFile = [INDEX_KEY, fileType].join('.') // return a function here - return baseFile => { - const failed = {ok: false}; - const files = compact(baseFile.replace(inDir, '').toLowerCase().split('/')) - const ctn = files.length; - const type = files[0]; - // we ignore all the files on the root level - if (files.length === 1) { - return failed; - } - const ext = '.' + fileType; - // process files within the folder of query, mutation, auth - const fileName = basename(files[1], ext) - // const evt = basename(files[1]); - switch (ctn) { - case 4: // this will definely inside the public folder - if (inTypesArray(type)) { - // we need to shift down one level to get the filename - const fileName4 = basename(files[2], ext) - let ok = (files[ctn - 1] === indexFile) - if (checkIfIsPublic(files, config)) { - // debug(4, _fileName, files); - return packOutput(type, fileName4, ok, baseFile, true, config) - } else if (checkIfIsPrivate(files, config)) { - return packOutput(type, fileName4, ok, baseFile, false, config) - } - } - // make sure it always terminate here - return failed; - case 3: // this could be inside the public folder - if (inTypesArray(type) || isAuthType(type, fileName, config)) { - let isPublic = checkIfIsPublic(files, config) - let isPrivate = checkIfIsPrivate(files, config) - let lastFile = files[ctn - 1]; - let ok = lastFile === indexFile; - let fileName3 = fileName; - if (isPublic || isPrivate) { - ok = true; - fileName3 = lastFile.replace(ext, '') - } - return packOutput(type, fileName3, ok, baseFile, isPublic, config) - } - case 2: - if (inTypesArray(type) || isAuthType(type, fileName, config)) { - // debug(2, type, fileName, files); - return packOutput(type, fileName, true, baseFile, false, config) - } - default: - return failed; + return checkResolver(indexFile, inDir, fileType, config) +} + +/** + * move from the process-files, the final step to process the resolver files to contract + * The parameter were pre-processed by the getResolver method + * @param {string} type of resolver + * @param {string} name of resolver + * @param {string} file resolver + * @param {boolean} public or private method + * @param {string} namespace if this is a socket + * @param {string} sourceType module or script + * @return {object} group together for merge + */ +function processResolverToContract(type, name, file, public, namespace, sourceType) { + // how do I change this to non-block instead? + const source = fsx.readFileSync(file, 'utf8').toString() + // parsing the file + const result = astParser(source, { sourceType }) + + // logToFile(config.logDirectory, [type, name].join('-'), result) + // get params @BUG the error happens here? + const baseParams = result.body.filter(isExpression).map(extractParams).filter(p => p) + const { description, params, returns } = getJsdoc(source, name) + // return + return { + [type]: { + [name]: { + namespace, + public, // mark if this is a public accessible method or not + file, + description, + params: merge([], baseParams[0], params), // merge array NOT OBJECT + returns: returns // merge({}, takeDownArray(returns), returns) + } } } } + +/** + * just return the base object for constructing the contract + * @param {string} sourceType module or script + * @return {object} the contract base + */ +function getContractBase(sourceType) { + return { + query: {}, + mutation: {}, + auth: {}, + timestamp: getTimestamp(), + sourceType: sourceType + } +} + // export -module.exports = getResolver; +module.exports = { + getResolver, + getSourceType, + getContractBase, + processResolverToContract +} diff --git a/packages/contract-cli/src/generator/hamsters/explain-resolver.js b/packages/contract-cli/src/generator/hamsters/explain-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..5effde7c9e5294565864af0894a3c607b594b2e3 --- /dev/null +++ b/packages/contract-cli/src/generator/hamsters/explain-resolver.js @@ -0,0 +1,18 @@ +// this will take the last preprocess output then pass to the jsdoc acron to +// get the part for the contract +const { getJsdoc } = require('../ast/jsdoc') + +/** + * The process listener + * @param {object} payload the complete payload + * @param {number} payload.idx the index of this process + * @param {string} payload.processor the name of the processor + * @param {array} payload.args the argument pass to the processor + * @return {void} just use process.send back the idx, processor and result + */ +process.on('message', ({ idx, processor, args }) => { + Reflect.apply(fn[processor], null, args) + .then(result => { + process.send({ idx, processor, result}) + }) +}) diff --git a/packages/contract-cli/src/generator/hamsters/preprocess-resolver.js b/packages/contract-cli/src/generator/hamsters/preprocess-resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..6b3707c720779bb01430edc8475b54a5eedcedf6 --- /dev/null +++ b/packages/contract-cli/src/generator/hamsters/preprocess-resolver.js @@ -0,0 +1,16 @@ +// this will take the input files list then check if this is a resolver + +/** + * The process listener + * @param {object} payload the complete payload + * @param {number} payload.idx the index of this process + * @param {string} payload.processor the name of the processor + * @param {array} payload.args the argument pass to the processor + * @return {void} just use process.send back the idx, processor and result + */ +process.on('message', ({ idx, processor, args }) => { + Reflect.apply(fn[processor], null, args) + .then(result => { + process.send({ idx, processor, result}) + }) +}) diff --git a/packages/contract-cli/src/generator/helpers.js b/packages/contract-cli/src/generator/helpers.js index be472f92463f1155f014711fbe93e4d6e4672e64..a65bf0ced425470708faaf162debe3fc931d7494 100644 --- a/packages/contract-cli/src/generator/helpers.js +++ b/packages/contract-cli/src/generator/helpers.js @@ -143,26 +143,6 @@ const takeDownArray = function(arr) { return arr; } -/** - * Control if we want to use jsdoc or not - * @param {object} config configuration props - * @param {object} result process result - * @param {string} source from function - * @param {string} name of function - * @return {object} with description, params, returns - */ -function extractExtraProps(config, result, source, name) { - // we force to use jsdoc api from v1.4.5 - return getJsdoc(source, name) - /* - if (config.useDoc) {} - return { - description: false, - params: [], - returns: result.body.filter(isExpression).map(tree => extractReturns(tree.expression)).filter(r => r) - }; */ -} - /** * V1.7.1 always add the sourceType for reference * inject extra to the contract.json file using the config @@ -203,7 +183,7 @@ module.exports = { packOutput, takeDownArray, - extractExtraProps, + mutateContract, logToFile, diff --git a/packages/contract-cli/src/generator/index.js b/packages/contract-cli/src/generator/index.js index a25253f79412b295773ac37278a0dfc77fd632c9..3bc41c1fc0f429996b2bd80d58ee6ffe76ee8f59 100644 --- a/packages/contract-cli/src/generator/index.js +++ b/packages/contract-cli/src/generator/index.js @@ -9,13 +9,13 @@ const { merge } = require('lodash') const colors = require('colors/safe') const debug = require('debug')('jsonql-contract:generator') + const { EXT, PUBLIC_CONTRACT_FILE_NAME } = require('jsonql-constants') -const publicContractGenerator = require('../public-contract') -const { - readFilesOutContract, - generateOutput, - isContractExisted -} = require('./files') + +const { publicContractGenerator } = require('../public-contract') +const { readFilesOutContract } = require('./read-files-out-contract') +const { generateOutput } = require('./generate-output') +const { isContractExisted } = require('./files-op') let ctn = 0; /** @@ -46,6 +46,7 @@ const banner = config => { */ const callPublicGenerator = (config, contract) => ( generateOutput( + contract.sourceType, merge({}, config, { outputFilename: PUBLIC_CONTRACT_FILE_NAME }), publicContractGenerator(config, contract), contract // <-- this is when ES6 module require to generate import export files @@ -60,11 +61,12 @@ const callPublicGenerator = (config, contract) => ( const generateNewContract = (config) => { const { resolverDir, contractDir } = config; return readFilesOutContract(resolverDir, config, config.ext || EXT) - .then(contract => { + .then(([sourceType, contract]) => { if (config.public === true) { + // we can get the sourceType from the contract return callPublicGenerator(config, contract) } - return generateOutput(config, contract) + return generateOutput(sourceType, config, contract) }) } diff --git a/packages/contract-cli/src/generator/process-file.js b/packages/contract-cli/src/generator/process-file.js new file mode 100644 index 0000000000000000000000000000000000000000..f02af34c495b66166f2aa3070bde40d49358f9e1 --- /dev/null +++ b/packages/contract-cli/src/generator/process-file.js @@ -0,0 +1,111 @@ +// this is the heart of the process that pass the resolver file into the AST to understand it +const { join, basename } = require('path') +const { merge } = require('lodash') +const { + getResolver, + getSourceType, + getContractBase, + processResolverToContract +} = require('./get-resolver') +const { splitTask } = require('./split-task') +// const { logToFile } = require('./helpers') +// const { astParser, extractReturns, extractParams, isExpression, getJsdoc } = require('../ast') +const { getDebug } = require('../utils') +const debug = getDebug('process-file') +// this was lost when using as api using let + +/** + * wrapper method to call the pre splitTask + * + */ +function callPreSplitTask(_files, _preprocessor) { + return splitTask('pre', { + files: _files, + preprocessor: _preprocessor + }) +} + +/** + * wrapper method to call the process splitTask + * + */ +function callPostSplitTask(_sourceType, _files, _config) { + return splitTask('process', { + sourceType: _sourceType, + files: _files, + config: _config + }) +} + +/** + * Take the map filter out to get the clean resolver objects + * @param {array} _files files to process + * @param {function} preprocessor for capture the resolver + * @return {array} resolver objects + */ +function processFilesAction(_files, _preprocessor) { + return callPreSplitTask(_files, _preprocessor) + .then(result => ( + result || _files.map( _preprocessor ) + .filter( obj => obj.ok ) + .reduce( (n, m) => [...n, m], []) + )) +} + +/** + * This is the step one to parallel process the resolver file + * @param {string} inDir where the resolverDir is + * @param {string} fileType extension to expect + * @param {array} _files to process + * @param {object} config options + * @return {array} of preprocessed filtered resolver + */ +function preprocessResolverFile(inDir, fileType, _files, config) { + const preprocessor = getResolver(inDir, fileType, config) + + return processFilesAction(_files, preprocessor) + .then(objs => [ + getSourceType(objs), + objs + ]) +} + +/** + * process the files + * @param {string} inDir base directory + * @param {string} fileType the ext + * @param {array} _files list of files + * @param {object} config to control the inner working + * @return {object} promise that resolve all the files key query / mutation + */ +function processResolverFile(sourceType, _files, config) { + return callPostSplitTask(sourceType, _files, config) + .then(result => ( + result || _files + .map(({ type, name, file, public, namespace }) => ( + processResolverToContract(type, name, file, public, namespace, resourceType) + )) + .reduce(merge, getContractBase(sourceType)) + )) +} + +/** + * when enableAuth !== true then we should remove the auth related methods + * @param {object} contract the generate contract json + * @param {object} config options + * @return {object} contract remove the auth if enableAuth !== true + */ +function postProcessResolverFile(contract, config) { + if (config.enableAuth !== true) { + contract.auth = {} + } + + return contract; +} + +// export +module.exports = { + preprocessResolverFile, + processResolverFile, + postProcessResolverFile +} diff --git a/packages/contract-cli/src/generator/read-files-out-contract.js b/packages/contract-cli/src/generator/read-files-out-contract.js new file mode 100644 index 0000000000000000000000000000000000000000..e9bc12817246818e7a4c5c70cbe1049b16b1f0b7 --- /dev/null +++ b/packages/contract-cli/src/generator/read-files-out-contract.js @@ -0,0 +1,63 @@ +// Here is the point where we need to split to load to different CPU +const { join, basename } = require('path') +const os = require('os') +const glob = require('glob') +const colors = require('colors/safe') +const { EXT } = require('jsonql-constants') + +const { + preprocessResolverFile, + processResolverFile +} = require('./process-file') +const { getDebug } = require('../utils') + +const debug = getDebug('read-files-out-contract') + +/** + * just return the list of files for process + * @param {string} inDir the path to the resolver directory + * @param {string} [fileType=EXT] the file extension + * @return {promise} resolve the files array on success or reject with error + */ +function getResolverFiles(inDir, fileType = EXT) { + const pat = join(inDir, '**', ['*', fileType].join('.')) + return new Promise((resolver, rejecter) => { + glob(pat, (err, files) => { + if (err) { + debug(`File read error!`, err) + return rejecter(err) + } + resolver(files) + }) + }) +} + +/** + * get list of files and put them in query / mutation + * @param {string} inDir diretory + * @param {object} config pass config to the underlying method + * @param {mixed} fileType we might do a ts in the future + * @return {object} query / mutation + */ +function readFilesOutContract(inDir, config, fileType) { + let timestart = Date.now() + return getResolverFiles(inDir, fileType) + .then(_files => ( + preprocessResolverFile(inDir, fileType, _files, config) + )) + .then(result => { + const [sourceType, files] = result; + return processResolverFile(sourceType, files, config) + .then(contract => [sourceType, contract]) + }) + .then(result => { + let timeend = Date.now() - timestart + debug('Time it took:', colors.yellow(timeend)) + return result + }) +} + +module.exports = { + getResolverFiles, // export for testing + readFilesOutContract +} diff --git a/packages/contract-cli/src/generator/split-task.js b/packages/contract-cli/src/generator/split-task.js new file mode 100644 index 0000000000000000000000000000000000000000..d8031c00c9a6455cfd6f212733c890072e673d20 --- /dev/null +++ b/packages/contract-cli/src/generator/split-task.js @@ -0,0 +1,113 @@ +// this will be responsible to split the task and run parallel computing to speed the task +const os = require('os') +const { fork } = require('child_process') +const { join } = require('path') +const { chainPromises } = require('jsonql-utils') + +const { getDebug } = require('../utils') + +const debug = getDebug('split-task') +const basePath = join(__dirname, 'hamsters') + +/** + * test if we have enough cpu slots + * @return {int} available cpu slots + */ +function getSlots() { + return os.cpus().length - 1; +} + +/** + * actually calling the task and return a promise that resolve result + * @param {string} taskPath file name of the method + * @param {*} payload to send to the task + * @return {promise} resolve the result or reject with error + */ +function executeTask(taskPath, payload) { + const ps = fork(join(basePath, `${taskPath}.js`)) + return new Promise((resolver, rejecter) => { + ps.send( payload ) + ps.on('message', result => { + resolver(result) + }) + ps.on('error', err => { + rejecter(err) + }) + }) +} + +/** + * create the task matrix + * @param {int} slots cpu slots + * @param {string} taskPath file name of the method + * @param {array} payloads array + * @param {boolean} returnType arry of object + * @return {promise} resolve the final result + */ +function createTask(slots, taskPath, payloads, returnType = true) { + let taskCtn = payloads.length; + let matrix = [] + let ctn = Math.ceil(taskCtn/slots) + for (let i=0; i= taskCtn) { + end = taskCtn; + } + matrix.push( + chainPromises(payloads.slice(begin, end).map(payload => { + executeTask(taskPath, payload) + }), returnType) + ) + } + // now futher process the final matrix + return chainPromises(matrix, returnType) +} + +/** + * The top level export method to get the task to do and array of payload + * @param {string} taskName the name of the task + * @param {array} payload array of payload + * @return {promise} resolve the final result + */ +function splitTask(taskName, payload) { + const slots = getSlots() + if ((slots > 0) === false) { + console.error(`Sorry your system does NOT support multi processing!`) + return false; + } + let returnType = true; + let scriptName, postProcessor; + let payloads = [] // prepare payload + switch (taskName) { + case 'process': + + return Promise.resolve(false) // stop it for testing + + scriptName = 'explain-resolver' + let { sourceType, config } = payload; + payloads = payload.files.map(file => ({ sourceType, file, config })) + postProcessor = result => result; + break; + case 'pre': + returnType = false; // default is array + scriptName = 'preprocess-resolver' + // here we need to get a preprocessor, then we don't need to keep calling it + let { files, preprocessor } = payload; + payloads = files.map(file => ({ file, preprocessor })) + postProcessor = result => { + // run the filter here + return result; + } + break; + default: + throw new Error(`Unknown task ${taskName}`) + } + // finally return + // return chainFns(createTask, postProcessor)(slots, scriptName, payloads) + return createTask(slots, scriptName, payloads, returnType) + .then(postProcessor) +} + +// export +module.exports = { splitTask } diff --git a/packages/contract-cli/src/public-contract/index.js b/packages/contract-cli/src/public-contract/index.js index cd6a602b9d242d6f537aa4f917cf66533427fbb5..66c483ea85122c29e26d4bce1f781a51b999ca37 100644 --- a/packages/contract-cli/src/public-contract/index.js +++ b/packages/contract-cli/src/public-contract/index.js @@ -86,7 +86,7 @@ function getExpired(config, contractJson) { * @param {object} contractJson the raw json file * @return {string} json */ -module.exports = function publicContractGenerator(config, contractJson) { +function publicContractGenerator(config, contractJson) { const contractDir = config.contractDir; if (!contractDir) { throw new JsonqlError('Contract directory is undefined!') @@ -109,3 +109,5 @@ module.exports = function publicContractGenerator(config, contractJson) { config ); } + +module.exports = { publicContractGenerator } diff --git a/packages/contract-cli/tests/koa-debug.test.js b/packages/contract-cli/tests/koa-debug.test.js index 81305157a526ad82f9dc6c3ff2d4bdfdce48cd31..e0345b84b1b7046bd3373c947bd8c9d8f9dc03c4 100644 --- a/packages/contract-cli/tests/koa-debug.test.js +++ b/packages/contract-cli/tests/koa-debug.test.js @@ -5,6 +5,7 @@ const { inspect } = require('util') const fsx = require('fs-extra') const debug = require('debug')('jsonql-contract:koa-debugging') +const contractApi = require('../index') const { contractGenerator } = require('../extra') const resolverDir = join(__dirname, 'fixtures', 'koa-resolvers') @@ -14,7 +15,19 @@ test.after(t => { fsx.removeSync(contractDir) }) -test(`It should able to generate a contract without error`, async t => { +test(`First test the contract api directly`, async t => { + const result = await contractApi({ + resolverDir, + contractDir, + returnAs: 'json' + }) + + debug(inspect(result, false, null)) + + t.truthy(result.mutation && result.mutation.updateMsService) +}) + +test.only(`It should able to generate a contract without error`, async t => { const result = await contractGenerator({ resolverDir, contractDir, @@ -23,5 +36,5 @@ test(`It should able to generate a contract without error`, async t => { debug(inspect(result, false, null)) - t.truthy(result.query) + t.truthy(result.mutation && result.mutation.updateMsService) }) diff --git a/packages/contract-cli/tests/split-task.test.js b/packages/contract-cli/tests/split-task.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ebf6bc27f4604686f7127fdbe7f11466945b00f0 --- /dev/null +++ b/packages/contract-cli/tests/split-task.test.js @@ -0,0 +1,66 @@ +// TDD to build the split task with cpu load caculcation and multiple +// array of promises +const test = require('ava') +const { chainPromises } = require('jsonql-utils') +const os = require('os') +const debug = require('debug')('jsonql-contract:test:split') +// import method frr testing +const { getResolverFiles } + + +function randomIntFromInterval(min, max) { // min and max included + return Math.floor(Math.random() * (max - min + 1) + min); +} + +test.before(t => { + const ctn = os.cpus().length - 1; + t.context.ctn = ctn; + // create 100 fake taskes + let taskes = [] + for (let i = 0; i < 100; ++i) { + taskes.push(() => { + let seed = randomIntFromInterval(1, 10) + return new Promise(resolver => { + setTimeout(() => { + resolver({ + ['msg' + i]: `This is task #${i} with random num ${seed}` + }) + }, 100*seed) + }) + }) + } + t.context.taskes = taskes +}) + +test.cb(`Should able to create multple array based on the cpu available`, t => { + t.plan(1) + + debug(`available task slot is ${t.context.ctn}`) + + let ctn = t.context.ctn; + let taskes = t.context.taskes; + let taskCtn = taskes.length; + + let matrix = []; + let slots = Math.ceil(taskCtn / ctn) + + debug(`Total slot is ${slots}`) + + let i = 0; + for (let j = 0; j < slots; ++j) { + let begin = j * ctn; + let end = begin + ctn; + if (end >= taskCtn) { + end = taskCtn; + } + matrix.push( + chainPromises(taskes.slice(begin, end).map(fn => fn()), {}) + ) + } + chainPromises(matrix) + .then(result => { + debug(result) + t.truthy( Array.isArray(result) ) + t.end() + }) +}) diff --git a/packages/node-client/package.json b/packages/node-client/package.json index 25bc255b12f7f7c7f141100de3dd5b027954c188..52ff4e1f19a715d8652aed9d3cbb155eafd4bf4f 100755 --- a/packages/node-client/package.json +++ b/packages/node-client/package.json @@ -1,10 +1,10 @@ { "name": "jsonql-node-client", - "version": "1.1.9", + "version": "1.1.10", "description": "jsonql node.js client using request", "main": "index.js", "scripts": { - "test": "ava --verbose", + "test": "DEBUG=jsonql* ava --verbose", "test:nyc": "DEBUG=jsonql-node-client* nyc ava", "test:main": "DEBUG=jsonql-node-client* ava tests/main.test.js", "test:auth": "DEBUG=jsonql-* ava tests/auth.test.js", @@ -39,21 +39,21 @@ "debug": "^4.1.1", "fs-extra": "^8.1.0", "jsonql-constants": "^1.8.3", - "jsonql-contract": "^1.7.12", "jsonql-errors": "^1.1.3", "jsonql-jwt": "^1.3.2", "jsonql-params-validator": "^1.4.11", "jsonql-utils": "^0.6.10", "lodash.merge": "^4.6.2", "node-cache": "^4.2.1", - "request": "^2.88.0", - "superkoa": "^1.0.3" + "request": "^2.88.0" }, "devDependencies": { "ava": "^2.4.0", - "jsonql-koa": "^1.3.8", + "jsonql-contract": "^1.7.15", + "jsonql-koa": "^1.3.9", "nyc": "^14.1.1", - "server-io-core": "^1.2.0" + "server-io-core": "^1.2.0", + "superkoa": "^1.0.3" }, "ava": { "files": [ diff --git a/packages/node-client/tests/auth.test.js b/packages/node-client/tests/auth.test.js index 8fc7432e6090451045a61d7ec25d6846139a990f..a2a52d5538e5fc035db1dbf71b0cd899eebab2e5 100755 --- a/packages/node-client/tests/auth.test.js +++ b/packages/node-client/tests/auth.test.js @@ -1,6 +1,7 @@ const test = require('ava') const { join } = require('path') const fs = require('fs') +const fsx = require('fs-extra') const debug = require('debug')('jsonql-node-client:test:auth') const { PUBLIC_CONTRACT_FILE_NAME } = require('jsonql-constants') const server = require('./fixtures/server-with-auth') @@ -26,6 +27,7 @@ test.before(async (t) => { test.after(t => { t.context.stop() + fsx.removeSync(contractDir) }) test('Testing the login function', async (t) => { diff --git a/packages/node-client/tests/config.test.js b/packages/node-client/tests/config.test.js index 3b402a53a769be18b84d94e5787b0e1c7baeecb0..5b76917b9d23ae01f0550ae3da16576838ae07fa 100644 --- a/packages/node-client/tests/config.test.js +++ b/packages/node-client/tests/config.test.js @@ -4,7 +4,7 @@ const { join } = require('path') const { checkOptions } = require('../src') let contractDir = join(__dirname, 'fixtures', 'contract', 'tmp') let hostname = 'http://localhost:8899'; -let contractKey = 'what-the-fuck-wrong-with-you-mother-fucker!'; +let contractKey = 'what-wrong-with-you-mf'; test('It should not throw Error', async t => { diff --git a/packages/node-client/tests/fixtures/contract-api.js b/packages/node-client/tests/fixtures/contract-api.js index 1503e1afea9753056e7e9680af85c5519dd8990b..0039d86c54a02ccd194268c715fc3ecf5c0e33a5 100644 --- a/packages/node-client/tests/fixtures/contract-api.js +++ b/packages/node-client/tests/fixtures/contract-api.js @@ -1,14 +1,14 @@ -const contractApi = require('jsonql-contract'); -const fsx = require('fs-extra'); -const { join } = require('path'); +const contractApi = require('jsonql-contract') +const fsx = require('fs-extra') +const { join } = require('path') module.exports = (clean = false) => { - const outDir = join(__dirname, 'contract', 'tmp' , 'server'); + const outDir = join(__dirname, 'contract', 'tmp' , 'server') if (clean === true) { - return fsx.removeSync(join(ourDir, 'contract.json')); + return fsx.removeSync(join(ourDir, 'contract.json')) } return contractApi({ inDir: join(__dirname, 'resolvers'), outDir - }).then(() => fsx.readJsonSync(join(outDir, 'contract.json')) ); -}; + }).then(() => fsx.readJsonSync(join(outDir, 'contract.json'))) +} diff --git a/packages/node-client/tests/fixtures/server-with-auth.js b/packages/node-client/tests/fixtures/server-with-auth.js index a9d5995b9d70cf111495f5fdb50f71beb57b0c77..5830a50a801fee5a912299296eb738b00779e526 100755 --- a/packages/node-client/tests/fixtures/server-with-auth.js +++ b/packages/node-client/tests/fixtures/server-with-auth.js @@ -1,5 +1,5 @@ const server = require('server-io-core') -const jsonql = require('./jsonql-koa') +const { jsonqlKoa } = require('./jsonql-koa') const { contractKey } = require('./options') const { join } = require('path') @@ -10,7 +10,7 @@ module.exports = function(port = 8889, extra = {}) { open: false, reload: false, middlewares: [ - jsonql(Object.assign({ + jsonqlKoa(Object.assign({ contractKey, resolverDir: join(__dirname,'resolvers'), contractDir: join(__dirname,'contract','tmp','server-with-auth'), diff --git a/packages/node-client/tests/fixtures/server.js b/packages/node-client/tests/fixtures/server.js index 89dcdbe457e0bdfa9a3c400f82cc95c09d3fb795..7964d77fbc3d0bcc6cfa2ddbfa49ca09b27d8a06 100755 --- a/packages/node-client/tests/fixtures/server.js +++ b/packages/node-client/tests/fixtures/server.js @@ -1,5 +1,5 @@ const server = require('server-io-core') -const jsonql = require('./jsonql-koa') +const { jsonqlKoa } = require('./jsonql-koa') const options = require('./options') const { join } = require('path') module.exports = function(port = 8888) { @@ -9,7 +9,7 @@ module.exports = function(port = 8888) { open: false, reload: false, middlewares: [ - jsonql({ + jsonqlKoa({ resolverDir: join(__dirname,'resolvers'), contractDir: join(__dirname,'contract','tmp' , 'server') }) diff --git a/packages/node-client/tests/fixtures/two/server-setup.js b/packages/node-client/tests/fixtures/two/server-setup.js index d4721725d1754b1922bc7bb13da6f9a1afc4b46c..2d834c747ff0fe88c3b5ed59dd92a8563ca67bb5 100644 --- a/packages/node-client/tests/fixtures/two/server-setup.js +++ b/packages/node-client/tests/fixtures/two/server-setup.js @@ -1,5 +1,5 @@ const server = require('server-io-core') -const koa = require('../../../../koa') +const { jsonqlKoa } = require('../jsonql-koa') const { join } = require('path') const dummy = join(__dirname, 'dummy') @@ -13,7 +13,7 @@ module.exports = (port, resolverDir, contractDir) => { socket: false, port: port, middlewares: [ - koa({ + jsonqlKoa({ name, resolverDir, contractDir diff --git a/packages/node-client/tests/jwt.test.js b/packages/node-client/tests/jwt.test.js index d878a8db57838dfc9fdce34a6dba1dca3107001f..b6d0f14e5670c20f305b26ad903335dfe46c2f2c 100644 --- a/packages/node-client/tests/jwt.test.js +++ b/packages/node-client/tests/jwt.test.js @@ -1,4 +1,5 @@ const test = require('ava') +const fsx = require('fs-extra') const { join } = require('path') const debug = require('debug')('jsonql-node-client:test:jwt') @@ -32,7 +33,10 @@ test.before(async t => { }) t.context.client = client; +}) +test.after(() => { + fsx.removeSync(contractDir) }) test.serial("It should able to login and received a token", async t => { diff --git a/packages/utils/browser.js b/packages/utils/browser.js index fa8399ac7aabef661236cc520ed75fa7083053ac..7e526b7a0dcf36bb25ebff0d8dd2ace8d4173f2b 100644 --- a/packages/utils/browser.js +++ b/packages/utils/browser.js @@ -1,2 +1,2 @@ -!function(r,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((r=r||self).jsonqlUtils={})}(this,(function(r){"use strict";var t=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")()).Symbol,a=Object.prototype,i=a.hasOwnProperty,c=a.toString,f=u?u.toStringTag:void 0;var s=Object.prototype.toString;var l="[object Null]",d="[object Undefined]",p=u?u.toStringTag:void 0;function v(r){return null==r?void 0===r?d:l:p&&p in Object(r)?function(r){var t=i.call(r,f),e=r[f];try{r[f]=void 0;var n=!0}catch(r){}var o=c.call(r);return n&&(t?r[f]=e:delete r[f]),o}(r):function(r){return s.call(r)}(r)}var y,g,h=(y=Object.getPrototypeOf,g=Object,function(r){return y(g(r))});function b(r){return null!=r&&"object"==typeof r}var m="[object Object]",j=Function.prototype,O=Object.prototype,w=j.toString,P=O.hasOwnProperty,S=w.call(Object);function N(r){if(!b(r)||v(r)!=m)return!1;var t=h(r);if(null===t)return!0;var e=P.call(t,"constructor")&&t.constructor;return"function"==typeof e&&e instanceof e&&w.call(e)==S}var _="[object Symbol]";var k=1/0,E=u?u.prototype:void 0,F=E?E.toString:void 0;function x(r){if("string"==typeof r)return r;if(t(r))return function(r,t){for(var e=-1,n=null==r?0:r.length,o=Array(n);++e=n?r:function(r,t,e){var n=-1,o=r.length;t<0&&(t=-t>o?0:o+t),(e=e>o?o:e)<0&&(e+=o),o=t>e?0:e-t>>>0,t>>>=0;for(var u=Array(o);++n-1;);return e}(o,u),function(r,t){for(var e=r.length;e--&&T(t,r[e],0)>-1;);return e}(o,u)+1).join("")}var L="[object String]";function Z(r){return"string"==typeof r||!t(r)&&b(r)&&v(r)==L}var G=function(r,t){return!!r.filter((function(r){return r===t})).length},W=function(r,t){var e=Object.keys(r);return G(e,t)},X=function(r){void 0===r&&(r=!1);var t=Date.now();return r?Math.floor(t/1e3):t},Y=function(r,t){var e=[];for(var n in t)e.push([n,t[n]].join("="));return[r,e.join("&")].join("?")},rr=function(){return{_cb:X()}},tr="query",er="mutation",nr="socket",or="payload",ur="condition",ar="resolverName",ir="args",cr=["POST","PUT"],fr=function(){try{if(window||document)return!0}catch(r){}return!1},sr=function(){try{if(!fr()&&e)return!0}catch(r){}return!1};var lr=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 fr()?"browser":sr()?"node":"unknown"},t}(Error),dr=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}(lr),pr=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}(lr),vr=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-1},Object.defineProperties(t,e),t}(lr);function yr(r){return N(r)&&(W(r,tr)||W(r,er)||W(r,nr))}function gr(r){return!!W(r,"socket")&&r.socket}var hr=function(r){return Z(r)?JSON.parse(r):r},br=function(r){var t;return(t={})[ir]=r,t};function mr(r){return Object.keys(r)[0]}function jr(r,e,n){var o;if(void 0===e&&(e=[]),void 0===n&&(n=!1),Z(r)&&t(e)){var u=br(e);return!0===n?u:((o={})[r]=u,o)}throw new pr("[createQuery] expect resolverName to be string and args to be array!",{resolverName:r,args:e})}function Or(r,t,e,n){var o;void 0===e&&(e={}),void 0===n&&(n=!1);var u={};if(u[or]=t,u[ur]=e,!0===n)return u;if(Z(r))return(o={})[r]=u,o;throw new pr("[createMutation] expect resolverName to be string!",{resolverName:r,payload:t,condition:e})}function wr(r,t){var e;if(r&&N(t)){var n=t[r];if(n[ir])return(e={})[ar]=r,e[ir]=n[ir],e}return!1}function Pr(r,t){var e=hr(r),n=mr(e);return Reflect.apply(t,null,[n,e])}function Sr(r,t){var e;if(r&&N(t)){var n=t[r];if(n)return(e={})[ar]=r,e[or]=n[or],e[ur]=n[ur],e}return!1}var Nr=yr;r.VERSION="0.6.10",r.cacheBurst=rr,r.cacheBurstUrl=function(r){return Y(r,rr())},r.chainFns=function(r){for(var t=[],e=arguments.length-1;e-- >0;)t[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return t.reduce((function(r,t){return Reflect.apply(t,null,[r])}),Reflect.apply(r,null,e))}},r.chainPromises=function(r){return r.reduce((function(r,t){return r.then((function(r){return t.then((function(t){return r.concat([t])}))}))}),Promise.resolve([]))},r.checkIsContract=yr,r.createEvt=function(){for(var r=[],t=arguments.length;t--;)r[t]=arguments[t];return r.join("_")},r.createMutation=Or,r.createMutationStr=function(r,t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),JSON.stringify(Or(r,t,e,n))},r.createQuery=jr,r.createQueryStr=function(r,t,e){return void 0===t&&(t=[]),void 0===e&&(e=!1),JSON.stringify(jr(r,t,e))},r.dasherize=function(r){return K(r).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},r.extractArgsFromPayload=function(r,t){switch(t){case tr:return r[ir];case er:return[r[or],r[ur]];default:throw new vr("Unknown "+t+" to extract argument from!")}},r.extractParamsFromContract=function(r,t,e){try{var n=r[t][e];if(!n)throw new dr(e,t);return n}catch(r){throw new dr(e,r)}},r.extractSocketPart=gr,r.formatPayload=br,r.getCallMethod=function(r){switch(!0){case r===cr[0]:return tr;case r===cr[1]:return er;default:return!1}},r.getConfigValue=function(r,t){return t&&N(t)&&r in t?t[r]:void 0},r.getMutationFromArgs=Sr,r.getMutationFromPayload=function(r){var t=Pr(r,Sr);if(!1!==t)return t;throw new pr("[getMutationArgs] Payload is malformed!",r)},r.getNameFromPayload=mr,r.getQueryFromArgs=wr,r.getQueryFromPayload=function(r){var t=Pr(r,wr);if(!1!==t)return t;throw new pr("[getQueryArgs] Payload is malformed!",r)},r.groupByNamespace=function(r,t){void 0===t&&(t=!1);var e=gr(r);if(!1===e){if(t)return r;throw new vr("socket not found in contract!")}var n,o={},u=0;for(var a in e){var i=e[a],c=i.namespace;c&&(o[c]||(++u,o[c]={}),o[c][a]=i,n||i.public&&(n=c))}return{size:u,nspSet:o,publicNamespace:n}},r.inArray=G,r.injectToFn=function(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)},r.isContract=Nr,r.isKeyInObject=W,r.isNotEmpty=function(r){return void 0!==r&&!1!==r&&null!==r&&""!==K(r)},r.objDefineProps=function(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},r.packError=function(r,t,e,n){var o;return void 0===t&&(t="JsonqlError"),void 0===e&&(e=500),void 0===n&&(n=""),JSON.stringify(((o={}).error={detail:r,className:t,statusCode:e,message:n},o))},r.packResult=function(r){var t;return JSON.stringify(((t={}).data=r,t))},r.resultHandler=function(r){return W(r,"data")&&!W(r,"error")?r.data:r},r.timestamp=X,r.toPayload=hr,r.urlParams=Y,Object.defineProperty(r,"__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,_=(h=Object.getPrototypeOf,b=Object,function(t){return h(b(t))});function g(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(!g(t)||y(t)!=j)return!1;var r=_(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 k="[object Symbol]";var z=1/0,E=i?i.prototype:void 0,N=E?E.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)&&g(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 _t(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return bt(e)?e:void 0}var gt=_t(u,"Map"),jt=_t(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 g(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>=Er)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(zr);function Tr(t,r){return xr(function(t,r,e){return r=kr(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,u=kr(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]):Mr(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 Br:return t[Gr];case Ir: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 Br;case t===Hr[1]:return Ir;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.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=Rr,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=le,t.isKeyInObject=Ur,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;return void 0===r&&(r="JsonqlError"),void 0===e&&(e=500),void 0===n&&(n=""),JSON.stringify(((o={}).error={detail:t,className:r,statusCode:e,message:n},o))},t.packResult=function(t){var r;return JSON.stringify(((r={}).data=t,r))},t.resultHandler=function(t){return Ur(t,"data")&&!Ur(t,"error")?t.data:t},t.timestamp=Jr,t.toPayload=ne,t.urlParams=$r,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=browser.js.map diff --git a/packages/utils/main.js b/packages/utils/main.js index d4c195b26ede7831036c466372a19f3e8bf0be8b..f59962f209c89e651dd532a86c1e5a8be050fd5f 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"),chainFns=function(r){for(var t=[],e=arguments.length-1;e-- >0;)t[e]=arguments[e+1];return function(){for(var e=[],n=arguments.length;n--;)e[n]=arguments[n];return t.reduce((function(r,t){return Reflect.apply(t,null,[r])}),Reflect.apply(r,null,e))}};function chainPromises(r){return r.reduce((function(r,t){return r.then((function(r){return t.then((function(t){return r.concat([t])}))}))}),Promise.resolve([]))}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 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 i=Array(o);++n=n?r:baseSlice(r,t,e)}function baseFindIndex(r,t,e,n){for(var o=r.length,i=e+(n?1:-1);n?i--:++i-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}var inArray=function(r,t){return!!r.filter((function(r){return r===t})).length},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},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({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,i=t.message||NO_ERROR_MSG,a=t.detail||t;if(o&&errors[o])throw new errors[e](i,a);throw new JsonqlError$1(i,a)}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({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={},i=0;for(var a in e){var s=e[a],u=s.namespace;u&&(o[u]||(++i,o[u]={}),o[u][a]=s,n||s.public&&(n=u))}return{size:i,nspSet:o,publicNamespace:n}}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 i={};if(i[PAYLOAD_PARAM_NAME]=t,i[CONDITION_PARAM_NAME]=e,!0===n)return i;if(isString(r))return(o={})[r]=i,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))},packError=function(r,t,e,n){var o;return void 0===t&&(t="JsonqlError"),void 0===e&&(e=500),void 0===n&&(n=""),JSON.stringify(((o={})[ERROR_KEY]={detail:r,className:t,statusCode:e,message:n},o))},resultHandler=function(r){return isKeyInObject(r,DATA_KEY)&&!isKeyInObject(r,ERROR_KEY)?r[DATA_KEY]:r},isContract=checkIsContract,VERSION="0.6.10",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");i="="===r[s-2]?2:"="===r[s-1]?1:0,a=new Arr(3*s/4-i),n=i>0?s-4:s;var u=0;for(t=0,e=0;t>16&255,a[u++]=o>>8&255,a[u++]=255&o;return 2===i?(o=revLookup[r.charCodeAt(t)]<<2|revLookup[r.charCodeAt(t+1)]>>4,a[u++]=255&o):1===i&&(o=revLookup[r.charCodeAt(t)]<<10|revLookup[r.charCodeAt(t+1)]<<4|revLookup[r.charCodeAt(t+2)]>>2,a[u++]=o>>8&255,a[u++]=255&o),a}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=[],i=t;is?s:a+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+="="),i.push(o),i.join("")}function read(r,t,e,n,o){var i,a,s=8*o-n-1,u=(1<>1,c=-7,l=e?o-1:0,h=e?-1:1,p=r[t+l];for(l+=h,i=p&(1<<-c)-1,p>>=-c,c+=s;c>0;i=256*i+r[t+l],l+=h,c-=8);for(a=i&(1<<-c)-1,i>>=-c,c+=n;c>0;a=256*a+r[t+l],l+=h,c-=8);if(0===i)i=1-f;else{if(i===u)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),i-=f}return(p?-1:1)*a*Math.pow(2,i-n)}function write(r,t,e,n,o,i){var a,s,u,f=8*i-o-1,c=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:i-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,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+l>=1?h/u:h*Math.pow(2,1-l))*u>=2&&(a++,u/=2),a+l>=c?(s=0,a=c):a+l>=1?(s=(t*u-1)*Math.pow(2,o),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),a=0));o>=8;r[e+p]=255&s,p+=g,s/=256,o-=8);for(a=a<0;r[e+p]=255&a,p+=g,a/=256,f-=8);r[e+p-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.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.from(t,n)),internalIsBuffer(t))return 0===t.length?-1:arrayIndexOf(r,t,e,n,o);if("number"==typeof t)return t&=255,Buffer.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 i,a=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;a=2,s/=2,u/=2,e/=2}function f(r,t){return 1===a?r[t]:r.readUInt16BE(t*a)}if(o){var c=-1;for(i=e;is&&(e=s-u),i=e;i>=0;i--){for(var l=!0,h=0;ho&&(n=o):n=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var a=0;a239?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&(i=r[o+1]))&&(u=(31&f)<<6|63&i)>127&&(c=u);break;case 3:i=r[o+1],a=r[o+2],128==(192&i)&&128==(192&a)&&(u=(15&f)<<12|(63&i)<<6|63&a)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:i=r[o+1],a=r[o+2],s=r[o+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(u=(15&f)<<18|(63&i)<<12|(63&a)<<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.TYPED_ARRAY_SUPPORT=void 0===global$1.TYPED_ARRAY_SUPPORT||global$1.TYPED_ARRAY_SUPPORT,Buffer.poolSize=8192,Buffer._augment=function(r){return r.__proto__=Buffer.prototype,r},Buffer.from=function(r,t,e){return from(null,r,t,e)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array),Buffer.alloc=function(r,t,e){return alloc(null,r,t,e)},Buffer.allocUnsafe=function(r){return allocUnsafe(null,r)},Buffer.allocUnsafeSlow=function(r){return allocUnsafe(null,r)},Buffer.isBuffer=isBuffer,Buffer.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,i=Math.min(e,n);o0&&(r=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(r+=" ... ")),""},Buffer.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 i=(o>>>=0)-(n>>>=0),a=(e>>>=0)-(t>>>=0),s=Math.min(i,a),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 i=!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(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Buffer.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="",i=t;ie)throw new RangeError("Trying to access beyond buffer length")}function checkInt(r,t,e,n,o,i){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,i=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,i=Math.min(r.length-e,4);o>>8*(n?o:3-o)&255}function checkIEEE754(r,t,e,n,o,i){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.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.prototype.readUInt8=function(r,t){return t||checkOffset(r,1,this.length),this[r]},Buffer.prototype.readUInt16LE=function(r,t){return t||checkOffset(r,2,this.length),this[r]|this[r+1]<<8},Buffer.prototype.readUInt16BE=function(r,t){return t||checkOffset(r,2,this.length),this[r]<<8|this[r+1]},Buffer.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.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.prototype.readIntLE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=this[r],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*t)),n},Buffer.prototype.readIntBE=function(r,t,e){r|=0,t|=0,e||checkOffset(r,t,this.length);for(var n=t,o=1,i=this[r+--n];n>0&&(o*=256);)i+=this[r+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(r,t){return t||checkOffset(r,1,this.length),128&this[r]?-1*(255-this[r]+1):this[r]},Buffer.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.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.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.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.prototype.readFloatLE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!0,23,4)},Buffer.prototype.readFloatBE=function(r,t){return t||checkOffset(r,4,this.length),read(this,r,!1,23,4)},Buffer.prototype.readDoubleLE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!0,52,8)},Buffer.prototype.readDoubleBE=function(r,t){return t||checkOffset(r,8,this.length),read(this,r,!1,52,8)},Buffer.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,i=0;for(this[t]=255&r;++i=0&&(i*=256);)this[t+o]=r/i&255;return t+e},Buffer.prototype.writeUInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),this[t]=255&r,t+1},Buffer.prototype.writeUInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer.prototype.writeUInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer.prototype.writeUInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer.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.prototype.writeUInt32BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,4294967295,0),Buffer.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.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 i=0,a=1,s=0;for(this[t]=255&r;++i>0)-s&255;return t+e},Buffer.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 i=e-1,a=1,s=0;for(this[t+i]=255&r;--i>=0&&(a*=256);)r<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(r/a>>0)-s&255;return t+e},Buffer.prototype.writeInt8=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(r=Math.floor(r)),r<0&&(r=255+r+1),this[t]=255&r,t+1},Buffer.prototype.writeInt16LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=255&r,this[t+1]=r>>>8):objectWriteUInt16(this,r,t,!0),t+2},Buffer.prototype.writeInt16BE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[t]=r>>>8,this[t+1]=255&r):objectWriteUInt16(this,r,t,!1),t+2},Buffer.prototype.writeInt32LE=function(r,t,e){return r=+r,t|=0,e||checkInt(this,r,t,4,2147483647,-2147483648),Buffer.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.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.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.prototype.writeFloatLE=function(r,t,e){return writeFloat(this,r,t,!0,e)},Buffer.prototype.writeFloatBE=function(r,t,e){return writeFloat(this,r,t,!1,e)},Buffer.prototype.writeDoubleLE=function(r,t,e){return writeDouble(this,r,t,!0,e)},Buffer.prototype.writeDoubleBE=function(r,t,e){return writeDouble(this,r,t,!1,e)},Buffer.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(i<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,e=void 0===e?this.length:e>>>0,r||(r=0),"number"==typeof r)for(i=t;i55295&&e<57344){if(!o){if(e>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(t-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((t-=1)<0)break;i.push(e)}else if(e<2048){if((t-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((t-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function asciiToBytes(r){for(var t=[],e=0;e>8,o=e%256,i.push(o),i.push(n);return i}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(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(r)?r:new Buffer.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.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),i=[];e.contract&&e.contract[t]&&e.contract[t].path&&i.push(e.contract[t].path),i.push(path.join(n,t,o,[INDEX_KEY,EXT].join(DOT))),i.push(path.join(n,t,[o,EXT].join(DOT)));for(var a=i.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},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},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({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({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 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))},packError=function(r,t,e,n){var o;return void 0===t&&(t="JsonqlError"),void 0===e&&(e=500),void 0===n&&(n=""),JSON.stringify(((o={})[ERROR_KEY]={detail:r,className:t,statusCode:e,message:n},o))},resultHandler=function(r){return isKeyInObject(r,DATA_KEY)&&!isKeyInObject(r,ERROR_KEY)?r[DATA_KEY]:r},isContract=checkIsContract,VERSION="0.6.12",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,h=e?-1:1,p=r[t+l];for(l+=h,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+r[t+l],l+=h,c-=8);for(i=a&(1<<-c)-1,a>>=-c,c+=n;c>0;i=256*i+r[t+l],l+=h,c-=8);if(0===a)a=1-f;else{if(a===u)return i?NaN:1/0*(p?-1:1);i+=Math.pow(2,n),a-=f}return(p?-1:1)*i*Math.pow(2,a-n)}function write(r,t,e,n,o,a){var i,s,u,f=8*a-o-1,c=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,g=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=c):(i=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-i))<1&&(i--,u*=2),(t+=i+l>=1?h/u:h*Math.pow(2,1-l))*u>=2&&(i++,u/=2),i+l>=c?(s=0,i=c):i+l>=1?(s=(t*u-1)*Math.pow(2,o),i+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),i=0));o>=8;r[e+p]=255&s,p+=g,s/=256,o-=8);for(i=i<0;r[e+p]=255&i,p+=g,i/=256,f-=8);r[e+p-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,h=0;ho&&(n=o):n=o;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var i=0;i239?4:f>223?3:f>191?2:1;if(o+l<=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":"6scAAAA,kvPCAA"} \ 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":"+l4BAAAA,kvPCAA"} \ No newline at end of file diff --git a/packages/utils/package.json b/packages/utils/package.json index d9e12ee2f0388a0037e5c9cb87bc5fd5fd447662..4a3e29e7558f32ebff389dbaee599a2fcc86ffb6 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,6 +1,6 @@ { "name": "jsonql-utils", - "version": "0.6.10", + "version": "0.6.12", "description": "This is a jsonql dependency module, not for generate use.", "main": "main.js", "module": "index.js", @@ -21,7 +21,8 @@ "build:client": "NODE_ENV=CLIENT rollup -c", "build": "npm run build:cjs && npm run build:umd", "test:define": "DEBUG=jsonql* ava --verbose ./tests/define-property.test.js", - "test:params": "DEBUG=jsonql* ava ./tests/params-api.test.js" + "test:params": "DEBUG=jsonql* ava ./tests/params-api.test.js", + "test:chain": "DEBUG=jsonql-utils* ava --verbose ./tests/chain-fn.test.js" }, "keywords": [ "jsonql", diff --git a/packages/utils/src/chain-fns.js b/packages/utils/src/chain-fns.js index 08b8209366ac158abc5bcb5b6a23db7cc7a51e35..101a70731d82b6da4ce4bd114492f62bf9a72e45 100644 --- a/packages/utils/src/chain-fns.js +++ b/packages/utils/src/chain-fns.js @@ -1,7 +1,7 @@ // break it out on its own because // it's building from the lodash-es from scratch // according to this discussion https://github.com/lodash/lodash/issues/3298 - +import { merge, isPlainObject } from './lodash' /** * using just the map reduce to chain multiple functions together * @param {function} mainFn the init function @@ -20,14 +20,17 @@ export const chainFns = (mainFn, ...moreFns) => ( * previously we already make sure the order of the namespaces * and attach the auth client to it * @param {array} promises array of unresolved promises + * @param {boolean} asObject if true then merge the result object * @return {object} promise resolved with the array of promises resolved results */ -export function chainPromises(promises) { +export function chainPromises(promises, asObject = false) { return promises.reduce((promiseChain, currentTask) => ( promiseChain.then(chainResults => ( currentTask.then(currentResult => ( - [...chainResults, currentResult] + asObject === false ? [...chainResults, currentResult] : merge(chainResults, currentResult) )) )) - ), Promise.resolve([])) + ), Promise.resolve( + asObject === false ? [] : (isPlainObject(asObject) ? asObject : {}) + )) } diff --git a/packages/utils/src/lodash.js b/packages/utils/src/lodash.js index 275c7b87862c785cd648c722b0483e4fbb8c11d1..63361bd9891495c518799a3b081c4f335aa13572 100644 --- a/packages/utils/src/lodash.js +++ b/packages/utils/src/lodash.js @@ -4,10 +4,12 @@ import isArray from 'lodash-es/isArray' import isPlainObject from 'lodash-es/isPlainObject' import trim from 'lodash-es/trim' import isString from 'lodash-es/isString' +import merge from 'lodash-es/merge' export { isArray, isPlainObject, isString, - trim + trim, + merge } diff --git a/packages/utils/tests/chain-fn.test.js b/packages/utils/tests/chain-fn.test.js index 4121d2e6d4bdd0aed9910ddd496b94b47f13ddc1..e0d55c39117aa7365b17bc810d1ec68309323b88 100644 --- a/packages/utils/tests/chain-fn.test.js +++ b/packages/utils/tests/chain-fn.test.js @@ -1,17 +1,27 @@ // need to test the chain-fns because of the way we change the lodash import const test = require('ava') -const { chainFns } = require('../src/chain-fns') +const { chainFns, chainPromises } = require('../src/chain-fns') +const debug = require('debug')('jsonql-utils:test:chain-fn') test('It should able to accept more than one functions after the first one', t => { - const baseFn = (num) => num * 10; const add1 = (num) => num + 1; const add2 = (num) => num + 2; const fn = chainFns(baseFn, add1, add2) - const result = fn(10) - t.is(103, result) +}) + +test(`It should able to merge the promise result together as one object`, async t => { + let ps = [] + for (let i = 0; i < 3; ++i) { + ps.push(Promise.resolve({['key' + i]: i})) + } + const result = await chainPromises(ps, {x: 'y'}) + + debug(result) + t.truthy( result['key1'] ) + t.true( result.x === 'y' ) })