diff --git a/grunt/config/esvm.js b/grunt/config/esvm.js index 1bd4a64ba..d67cca51f 100644 --- a/grunt/config/esvm.js +++ b/grunt/config/esvm.js @@ -1,11 +1,11 @@ -var get = require('lodash.get'); -var utils = require('../utils'); +var _ = require('lodash'); +var gruntUtils = require('../utils'); var fromRoot = require('path').join.bind(null, __dirname, '..', '..'); var release = process.env.ES_RELEASE; var ref = process.env.ES_REF; -var port = parseFloat(get(process.env, 'ES_PORT', 9400)); -var host = get(process.env, 'ES_HOST', 'localhost'); +var port = parseFloat(_.get(process.env, 'ES_PORT', 9400)); +var host = _.get(process.env, 'ES_HOST', 'localhost'); var Version = require('../../scripts/Version'); var versionedOpts = [ @@ -78,7 +78,7 @@ var versionedOpts = [ ]; // targets for each branch -utils.branches.forEach(function (branch) { +gruntUtils.branches.forEach(function (branch) { exports[branch] = { options: Version.fromBranch(branch).mergeOpts(versionedOpts, { branch: branch, diff --git a/grunt/config/mochacov.js b/grunt/config/mochacov.js index dd896a0a7..aade288a1 100644 --- a/grunt/config/mochacov.js +++ b/grunt/config/mochacov.js @@ -1,7 +1,7 @@ var root = require('find-root')(__dirname); var rel = require('path').resolve.bind(null, root); var rootReq = function (p) { return require(rel(p)); }; -var _ = rootReq('src/lib/utils'); +var utils = rootReq('src/lib/utils'); var grunt = require('grunt'); var JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js'); @@ -65,7 +65,7 @@ var config = { grunt.registerTask('mocha_integration', function (branch) { grunt.config.set( 'mochacov.integration.src', - 'test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js' + 'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js' ); grunt.task.run('mochacov:integration'); }); @@ -73,7 +73,7 @@ grunt.registerTask('mocha_integration', function (branch) { grunt.registerTask('mocha_jenkins_integration', function (branch) { grunt.config.set( 'mochacov.jenkins_integration.src', - 'test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js' + 'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js' ); grunt.task.run('mochacov:jenkins_integration'); }); diff --git a/grunt/config/run.js b/grunt/config/run.js index 053d522ff..6f60eb15e 100644 --- a/grunt/config/run.js +++ b/grunt/config/run.js @@ -1,4 +1,4 @@ -var utils = require('../utils'); +var gruntUtils = require('../utils'); var config = { generate: { @@ -52,7 +52,7 @@ var config = { } }; -utils.branches.forEach(function (branch) { +gruntUtils.branches.forEach(function (branch) { config['generate_' + branch] = { exec: 'node ./scripts/generate/index.js --branch=' + branch }; diff --git a/grunt/tasks.js b/grunt/tasks.js index ddd797f3a..5a10c4e46 100644 --- a/grunt/tasks.js +++ b/grunt/tasks.js @@ -1,6 +1,6 @@ module.exports = function (grunt) { var Promise = require('bluebird'); - var utils = require('./utils'); + var gruntUtils = require('./utils'); var readFile = Promise.promisify(require('fs').readFile); var writeFile = Promise.promisify(require('fs').writeFile); @@ -16,7 +16,7 @@ module.exports = function (grunt) { 'mochacov:unit' ]; - var branches = branch ? [branch] : utils.branches; + var branches = branch ? [branch] : gruntUtils.branches; process.env.ES_PORT = process.env.ES_PORT || 9400; process.env.ES_HOST = process.env.ES_HOST || 'localhost'; @@ -52,20 +52,20 @@ module.exports = function (grunt) { var current = pkg.version; pkg.version = nextVersion; - browserBuilds = utils.replaceAll(browserBuilds, current, nextVersion); + browserBuilds = gruntUtils.replaceAll(browserBuilds, current, nextVersion); - readme = utils.replaceAll(readme, current, nextVersion); + readme = gruntUtils.replaceAll(readme, current, nextVersion); - readme = utils.replaceAll( + readme = gruntUtils.replaceAll( readme, - '/' + utils.minorVersion(current) + '.svg', - '/' + utils.minorVersion(nextVersion) + '.svg' + '/' + gruntUtils.minorVersion(current) + '.svg', + '/' + gruntUtils.minorVersion(nextVersion) + '.svg' ); - readme = utils.replaceAll( + readme = gruntUtils.replaceAll( readme, - 'branch=' + utils.minorVersion(current), - 'branch=' + utils.minorVersion(nextVersion) + 'branch=' + gruntUtils.minorVersion(current), + 'branch=' + gruntUtils.minorVersion(nextVersion) ); // write all files to disk diff --git a/grunt/utils.js b/grunt/utils.js index a880791b6..660af964a 100644 --- a/grunt/utils.js +++ b/grunt/utils.js @@ -1,4 +1,4 @@ -var _ = require('../src/lib/utils'); +var utils = require('../src/lib/utils'); var root = require('find-root')(__dirname); var pkg = require(root + '/package.json'); @@ -6,9 +6,9 @@ var stable = pkg.config.supported_es_branches; var unstable = pkg.config.unstable_es_branches; var branches = [].concat(stable, unstable); -var utils = { +var gruntUtils = { branchSuffix: function (branch) { - return branch === utils.branches._default ? '' : '_' + _.snakeCase(branch); + return branch === gruntUtils.branches._default ? '' : '_' + utils.snakeCase(branch); }, branches: branches, stableBranches: stable, @@ -16,19 +16,19 @@ var utils = { browserBranches: stable.slice(0, 5).concat(unstable) }; -utils.branches._default = pkg.config.default_api_branch; +gruntUtils.branches._default = pkg.config.default_api_branch; /* * trim down a version id to the minor version number ('1.5.1' => '1.5') */ -utils.minorVersion = function (version) { +gruntUtils.minorVersion = function (version) { return version.split('.').slice(0, 2).join('.'); }; /* * increment the version based on the release "type" */ -utils.increaseVersion = function (version, type) { +gruntUtils.increaseVersion = function (version, type) { var i; switch (type) { case 'major': @@ -62,7 +62,7 @@ utils.increaseVersion = function (version, type) { /* * replace all instances of `replace` with `replacement` without creating a regexp object */ -utils.replaceAll = function (str, replace, replacement) { +gruntUtils.replaceAll = function (str, replace, replacement) { var out = ''; var remaining = str; var i = 0; @@ -75,4 +75,4 @@ utils.replaceAll = function (str, replace, replacement) { return out + remaining; }; -module.exports = utils; +module.exports = gruntUtils; diff --git a/package.json b/package.json index 072607718..a551c923d 100644 --- a/package.json +++ b/package.json @@ -105,10 +105,7 @@ "dependencies": { "agentkeepalive": "^3.4.1", "chalk": "^1.0.0", - "lodash": "2.4.2", - "lodash.get": "^4.4.2", - "lodash.isempty": "^4.4.0", - "lodash.trimend": "^4.5.1" + "lodash": "^4.17.10" }, "resolutions": { "grunt-webpack/deep-for-each": "https://github.com/spalger/js-deep-for-each/releases/download/v2.0.2-fix-missing-lodash-dep/deep-for-each-2.0.2.tgz" @@ -126,4 +123,4 @@ "engines": { "node": ">=0.8" } -} \ No newline at end of file +} diff --git a/scripts/generate/api_index.js b/scripts/generate/api_index.js index ef538c0ac..8ac27b02d 100644 --- a/scripts/generate/api_index.js +++ b/scripts/generate/api_index.js @@ -1,6 +1,6 @@ module.exports = function (done) { - var _ = require('../../src/lib/utils'); - var utils = require('../../grunt/utils'); + var _ = require('lodash'); + var gruntUtils = require('../../grunt/utils'); var chalk = require('chalk'); var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); @@ -10,13 +10,13 @@ module.exports = function (done) { var browserApiIndex = fromRoot('src/lib/apis/browser_index.js'); write(nodeApiIndex, require('./templates').apiIndex({ - branches: utils.branches + branches: gruntUtils.branches }), 'utf8'); console.log(chalk.white.bold('wrote'), 'api index to', nodeApiIndex); write(browserApiIndex, require('./templates').apiIndexBrowser({ - branches: utils.browserBranches + branches: gruntUtils.browserBranches }), 'utf8'); console.log(chalk.white.bold('wrote'), 'browser api index to', browserApiIndex); diff --git a/scripts/generate/configuration_docs.js b/scripts/generate/configuration_docs.js index 939e8bdae..212ba9a2e 100644 --- a/scripts/generate/configuration_docs.js +++ b/scripts/generate/configuration_docs.js @@ -1,5 +1,5 @@ module.exports = function (done) { - var _ = require('../../src/lib/utils'); + var _ = require('lodash'); var chalk = require('chalk'); var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); diff --git a/scripts/generate/doc_index.js b/scripts/generate/doc_index.js index 07cea06f2..d359219bb 100644 --- a/scripts/generate/doc_index.js +++ b/scripts/generate/doc_index.js @@ -1,6 +1,6 @@ module.exports = function (done) { - var _ = require('../../src/lib/utils'); - var utils = require('../../grunt/utils'); + var _ = require('lodash'); + var gruntUtils = require('../../grunt/utils'); var chalk = require('chalk'); var fromRoot = _.partial(require('path').join, require('find-root')(__dirname)); @@ -9,8 +9,8 @@ module.exports = function (done) { var outputPath = fromRoot('docs/index.asciidoc'); write(outputPath, require('./templates').docsIndex({ - apiFiles: utils.stableBranches.map(function (branch) { - return 'api_methods' + utils.branchSuffix(branch) + '.asciidoc'; + apiFiles: gruntUtils.stableBranches.map(function (branch) { + return 'api_methods' + gruntUtils.branchSuffix(branch) + '.asciidoc'; }) }), 'utf8', done); diff --git a/scripts/generate/index.js b/scripts/generate/index.js index 95f385255..93a384f66 100644 --- a/scripts/generate/index.js +++ b/scripts/generate/index.js @@ -29,8 +29,9 @@ var argv = require('optimist') var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); -var utils = require(fromRoot('grunt/utils')); -var _ = require(fromRoot('src/lib/utils')); +var _ = require('lodash'); +var utils = require(fromRoot('src/lib/utils')); +var gruntUtils = require(fromRoot('grunt/utils')); var esUrl = process.env.ES_REPO ? path.resolve(process.cwd(), process.env.ES_REPO) : 'https://github.com/elastic/elasticsearch.git'; @@ -48,7 +49,7 @@ if (process.env.npm_config_argv) { if (argv.branch) { branches = [argv.branch]; } else { - branches = utils.branches; + branches = gruntUtils.branches; } var paths = { @@ -59,10 +60,10 @@ var paths = { docsIndex: fromRoot('docs/index.asciidoc'), apiSrc: 'src/lib/apis', getArchiveDir: function (branch) { - return fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); + return fromRoot('src/_elasticsearch_' + utils.snakeCase(branch)); }, getArchiveTarball: function (branch) { - return fromRoot('src/_elasticsearch_' + _.snakeCase(branch) + '.tar'); + return fromRoot('src/_elasticsearch_' + utils.snakeCase(branch) + '.tar'); }, getSpecPathInRepo: function (branch) { return /^v?(master|[2-9]\.)/.test(branch) ? 'rest-api-spec/src/main/resources/rest-api-spec' : 'rest-api-spec'; @@ -98,7 +99,7 @@ function dirRegex(dir, regexp) { function dirOpts(dir, opts) { opts = _.isArray(opts) ? opts : [opts]; return dirFilter(dir, function (name) { - return _.include(opts, name); + return _.includes(opts, name); }); } @@ -137,7 +138,7 @@ function fetchBranchesStep() { function findGeneratedApiFiles() { var anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/; var anyApiJsFiled = /^.+\.js$/; - var allBranches = _.isEqual(branches, utils.branches); + var allBranches = _.isEqual(branches, gruntUtils.branches); if (allBranches) { return [ @@ -147,11 +148,11 @@ function findGeneratedApiFiles() { } return branches.reduce(function (files, branch) { - var b = _.snakeCase(branch); + var b = utils.snakeCase(branch); files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc')); - var isDefault = branch === utils.branches._default; + var isDefault = branch === gruntUtils.branches._default; if (isDefault) { files.push(dirOpts(paths.docs, 'api_methods.asciidoc')); } diff --git a/scripts/generate/js_api.js b/scripts/generate/js_api.js index fbdcf8a2d..3867e4365 100644 --- a/scripts/generate/js_api.js +++ b/scripts/generate/js_api.js @@ -3,8 +3,9 @@ module.exports = function (branch, done) { * Read the API actions form the rest-api-spec repo. * @type {[type]} */ - var _ = require('../../src/lib/utils'); - var utils = require('../../grunt/utils'); + var _ = require('lodash'); + var utils = require('../../src/lib/utils'); + var gruntUtils = require('../../grunt/utils'); var fs = require('fs'); var async = require('async'); var chalk = require('chalk'); @@ -18,8 +19,8 @@ module.exports = function (branch, done) { var apiSpec; // populated by parseSpecFiles var docVars; // slightly modified clone of apiSpec for the docs - var branchSuffix = utils.branchSuffix(branch); - var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); + var branchSuffix = gruntUtils.branchSuffix(branch); + var esDir = fromRoot('src/_elasticsearch_' + utils.snakeCase(branch)); var version = Version.fromBranch(branch); var overrides = version.mergeOpts(require('./overrides'), { @@ -39,7 +40,7 @@ module.exports = function (branch, done) { writeApiFile ]; - if (!~utils.unstableBranches.indexOf(branch)) { + if (!~gruntUtils.unstableBranches.indexOf(branch)) { steps.push( ensureDocsDir, formatDocVars, @@ -137,7 +138,7 @@ module.exports = function (branch, done) { } function writeApiFile(done) { - var outputPath = fromRoot('src/lib/apis/' + _.snakeCase(branch) + '.js'); + var outputPath = fromRoot('src/lib/apis/' + utils.snakeCase(branch) + '.js'); fs.writeFileSync(outputPath, templates.apiFile(apiSpec)); console.log(chalk.white.bold('wrote'), apiSpec.actions.length, 'api actions to', outputPath); done(); @@ -169,7 +170,7 @@ module.exports = function (branch, done) { 'name' ); docVars.branch = branch; - docVars.branchIsDefault = branch === utils.branches._default; + docVars.branchIsDefault = branch === gruntUtils.branches._default; docVars.branchSuffix = branchSuffix.replace(/_/g, '-'); done(); } @@ -194,7 +195,7 @@ module.exports = function (branch, done) { // itterate all of the specs within the file, should only be one _.each(spec, function (def, name) { // camelcase the name - name = _.map(name.split('.'), _.camelCase).join('.'); + name = _.map(name.split('.'), utils.camelCase).join('.'); if (name === 'cat.aliases') { def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html'; @@ -208,7 +209,7 @@ module.exports = function (branch, done) { var steps = name.split('.'); function transformParamKeys(note, param, key) { - var cmlKey = _.camelCase(key); + var cmlKey = utils.camelCase(key); if (cmlKey !== key) { param.name = key; } @@ -222,7 +223,7 @@ module.exports = function (branch, done) { _.forOwn(allParams, (paramSpec, paramName) => { const toMerge = _.get(overrides, ['mergeConcatParams', name, paramName]) if (toMerge) { - _.merge(paramSpec, toMerge, (dest, src) => { + _.mergeWith(paramSpec, toMerge, (dest, src) => { if (_.isArray(dest) && _.isArray(src)) { return dest.concat(src) } @@ -240,7 +241,7 @@ module.exports = function (branch, done) { methods: _.map(def.methods, function (m) { return m.toUpperCase(); }), params: def.url.params, body: def.body || null, - path2lib: _.repeat('../', steps.length + 1) + 'lib/' + path2lib: utils.repeat('../', steps.length + 1) + 'lib/' }; if (def.body && def.body.required) { @@ -270,17 +271,17 @@ module.exports = function (branch, done) { } while (match = urlParamRE.exec(url)) { - name = _.camelCase(match[1]); + name = utils.camelCase(match[1]); param = def.url.parts[name] || {}; target = (param.required || !param.default) ? requiredVars : optionalVars; - target[name] = _.omit(param, 'required', 'description', 'name'); + target[name] = _.omit(param, ['required', 'description', 'name']); } urlSignatures.push(_.union(_.keys(optionalVars), _.keys(requiredVars)).sort().join(':')); - return _.omit({ + return _.omitBy({ fmt: url.replace(urlParamRE, function (full, match) { - return '<%=' + _.camelCase(match) + '%>'; + return '<%=' + utils.camelCase(match) + '%>'; }), opt: _.size(optionalVars) ? optionalVars : null, req: _.size(requiredVars) ? requiredVars : null, diff --git a/scripts/generate/overrides.js b/scripts/generate/overrides.js index 91a1dce5d..45f366571 100644 --- a/scripts/generate/overrides.js +++ b/scripts/generate/overrides.js @@ -191,7 +191,7 @@ module.exports = [ /* eslint-disable */ clientActionModifier: function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/scripts/generate/templates/api_file.tmpl b/scripts/generate/templates/api_file.tmpl index 569de5035..2770efdfc 100644 --- a/scripts/generate/templates/api_file.tmpl +++ b/scripts/generate/templates/api_file.tmpl @@ -15,8 +15,8 @@ _.each(actions, function (action) { .slice(0, -1) .filter(step => step !== 'prototype') .join('.prototype.'); - - if (_.include(namespaces, namespace)) { + + if (_.includes(namespaces, namespace)) { _.pull(namespaces, namespace); %> diff --git a/scripts/generate/templates/api_index.tmpl b/scripts/generate/templates/api_index.tmpl index f269c4ddb..97af755b9 100644 --- a/scripts/generate/templates/api_index.tmpl +++ b/scripts/generate/templates/api_index.tmpl @@ -4,10 +4,10 @@ module.exports = { branches.forEach(function (branch, i, list) { function printVersion(name) { - print(` get '${name}'() { return require('./${_.snakeCase(branch)}'); },\n`) + print(` get '${name}'() { return require('./${utils.snakeCase(branch)}'); },\n`) } - if (branch === utils.branches._default) printVersion('_default'); + if (branch === gruntUtils.branches._default) printVersion('_default'); printVersion(branch); }); diff --git a/scripts/generate/templates/api_index_browser.tmpl b/scripts/generate/templates/api_index_browser.tmpl index 60e14139c..78b55452e 100644 --- a/scripts/generate/templates/api_index_browser.tmpl +++ b/scripts/generate/templates/api_index_browser.tmpl @@ -2,8 +2,8 @@ module.exports = { <% branches.forEach(function (branch, i, list) { - var req = "require('./" + _.snakeCase(branch) + "')"; - if (branch === utils.branches._default) { + var req = "require('./" + utils.snakeCase(branch) + "')"; + if (branch === gruntUtils.branches._default) { print(" '_default': " + req + ',\n'); } diff --git a/scripts/generate/templates/configuration_docs.tmpl b/scripts/generate/templates/configuration_docs.tmpl index 9ef8d13e2..2d30b29af 100644 --- a/scripts/generate/templates/configuration_docs.tmpl +++ b/scripts/generate/templates/configuration_docs.tmpl @@ -52,12 +52,12 @@ Default in Node::: + WARNING: This default will track the latest version of Elasticsearch, and is only intended to be used during development. It is highly recommended that you set this parameter in all code that is headed to production. -Default ::: `<%= stringify(utils.branches._default) %>` +Default ::: `<%= stringify(gruntUtils.branches._default) %>` <% function printBranch(branch, i) { print(' * `' + stringify(branch) + '`'); - if (utils.unstableBranches.indexOf(branch) >= 0) { + if (gruntUtils.unstableBranches.indexOf(branch) >= 0) { print(' (unstable)'); } print('\n'); @@ -65,9 +65,9 @@ function printBranch(branch, i) { %> Options in node ::: -<% utils.branches.forEach(printBranch); %> +<% gruntUtils.branches.forEach(printBranch); %> Options in the browser ::: -<% utils.browserBranches.forEach(printBranch); %> +<% gruntUtils.browserBranches.forEach(printBranch); %> `plugins`[[config-plugins]]:: `Function[]` -- Plugin instantiators that will be called when the Client initializes. Each function is called in order with the arguments `Constructor`, `config`, and `components`. @@ -319,7 +319,7 @@ var client = new elasticsearch.Client({ // choose the node with the smallest weight. selection = _(nodes).sortBy(function (node) { return node.host.weight; - }).first(); + }).head(); } return selection; diff --git a/scripts/generate/templates/index.js b/scripts/generate/templates/index.js index aec6069dd..2495abc35 100644 --- a/scripts/generate/templates/index.js +++ b/scripts/generate/templates/index.js @@ -1,6 +1,7 @@ -var _ = require('../../../src/lib/utils'); -var utils = require('../../../grunt/utils'); +var _ = require('lodash'); +var utils = require('../../../src/lib/utils'); +var gruntUtils = require('../../../grunt/utils'); var fs = require('fs'); var path = require('path'); @@ -42,9 +43,10 @@ var templateGlobals = { stringify: stringify, _: _, + utils: utils, indent: function (block, spaces) { - var indent = _.repeat(' ', spaces); + var indent = utils.repeat(' ', spaces); return block.split('\n').map(function (line) { return indent + line; }).join('\n'); @@ -92,7 +94,7 @@ var templateGlobals = { partials: templates, - utils: utils + gruntUtils: gruntUtils }; fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) { @@ -100,7 +102,6 @@ fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) { if (name !== 'index') { templates[name] = _.template( fs.readFileSync(path.resolve(__dirname, filename), 'utf8'), - null, { imports: templateGlobals } diff --git a/scripts/generate/yaml_tests.js b/scripts/generate/yaml_tests.js index 093695b1a..247756feb 100644 --- a/scripts/generate/yaml_tests.js +++ b/scripts/generate/yaml_tests.js @@ -8,10 +8,10 @@ module.exports = function (branch, done) { var chalk = require('chalk'); var path = require('path'); var fromRoot = path.join.bind(path, require('find-root')(__dirname)); - var _ = require(fromRoot('src/lib/utils')); + var utils = require(fromRoot('src/lib/utils')); var tests = {}; // populated in readYamlTests - var esDir = fromRoot('src/_elasticsearch_' + _.snakeCase(branch)); + var esDir = fromRoot('src/_elasticsearch_' + utils.snakeCase(branch)); // generate the yaml tests async.series([ @@ -43,14 +43,14 @@ module.exports = function (branch, done) { } function writeYamlTests(done) { - var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + _.snakeCase(branch) + '.json'); + var testFile = fromRoot('test/integration/yaml_suite/yaml_tests_' + utils.snakeCase(branch) + '.json'); fs.writeFileSync(testFile, JSON.stringify(tests, null, ' '), 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML tests as JSON to', testFile); done(); } function writeTestIndex(done) { - var file = fromRoot('test/integration/yaml_suite/index_' + _.snakeCase(branch) + '.js'); + var file = fromRoot('test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js'); fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8'); console.log(chalk.white.bold('wrote') + ' YAML index to', file); done(); diff --git a/src/lib/apis/1_7.js b/src/lib/apis/1_7.js index ff0c01133..d61cd16d8 100644 --- a/src/lib/apis/1_7.js +++ b/src/lib/apis/1_7.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/2_4.js b/src/lib/apis/2_4.js index e597b172b..34b03c7df 100644 --- a/src/lib/apis/2_4.js +++ b/src/lib/apis/2_4.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_0.js b/src/lib/apis/5_0.js index f478b03aa..d35f30122 100644 --- a/src/lib/apis/5_0.js +++ b/src/lib/apis/5_0.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_1.js b/src/lib/apis/5_1.js index 7f295a602..300c33abc 100644 --- a/src/lib/apis/5_1.js +++ b/src/lib/apis/5_1.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_2.js b/src/lib/apis/5_2.js index 93125c76f..fb3c9a34c 100644 --- a/src/lib/apis/5_2.js +++ b/src/lib/apis/5_2.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_3.js b/src/lib/apis/5_3.js index 2fcb9cfa2..1f910db73 100644 --- a/src/lib/apis/5_3.js +++ b/src/lib/apis/5_3.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_4.js b/src/lib/apis/5_4.js index 15db9d71f..d12613584 100644 --- a/src/lib/apis/5_4.js +++ b/src/lib/apis/5_4.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_5.js b/src/lib/apis/5_5.js index 1cddf586b..4fa4102b7 100644 --- a/src/lib/apis/5_5.js +++ b/src/lib/apis/5_5.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/5_6.js b/src/lib/apis/5_6.js index 2bf813a3a..70f428538 100644 --- a/src/lib/apis/5_6.js +++ b/src/lib/apis/5_6.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/6_0.js b/src/lib/apis/6_0.js index 05b578d89..335d3e000 100644 --- a/src/lib/apis/6_0.js +++ b/src/lib/apis/6_0.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/6_1.js b/src/lib/apis/6_1.js index c4ec74f7c..0144889c0 100644 --- a/src/lib/apis/6_1.js +++ b/src/lib/apis/6_1.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/6_2.js b/src/lib/apis/6_2.js index 89ebfe1e6..bb2035235 100644 --- a/src/lib/apis/6_2.js +++ b/src/lib/apis/6_2.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/6_x.js b/src/lib/apis/6_x.js index 2a2e75f3b..eacd0d1d1 100644 --- a/src/lib/apis/6_x.js +++ b/src/lib/apis/6_x.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/apis/master.js b/src/lib/apis/master.js index 705d5c3c5..2a8341844 100644 --- a/src/lib/apis/master.js +++ b/src/lib/apis/master.js @@ -1,5 +1,5 @@ var ca = require('../client_action').makeFactoryWithModifier(function (spec) { - return require('../utils').merge(spec, { + return require('lodash').merge(spec, { params: { filterPath: { type: 'list', diff --git a/src/lib/client.js b/src/lib/client.js index a50c869ac..b3bbd7832 100755 --- a/src/lib/client.js +++ b/src/lib/client.js @@ -28,7 +28,8 @@ module.exports = Client; var Transport = require('./transport'); var clientAction = require('./client_action'); -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); function Client(config) { config = config || {}; @@ -66,7 +67,7 @@ function Client(config) { } - EsApiClient.prototype = _.funcEnum(config, 'apiVersion', Client.apis, '_default'); + EsApiClient.prototype = utils.funcEnum(config, 'apiVersion', Client.apis, '_default'); if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) { config.sniffEndpoint = '/_cluster/nodes'; } @@ -92,8 +93,7 @@ function Client(config) { Log: require('./log'), Logger: require('./logger'), NodesToHost: require('./nodes_to_host'), - Transport: require('./transport'), - utils: require('./utils') + Transport: require('./transport') }) || Constructor; }); } diff --git a/src/lib/client_action.js b/src/lib/client_action.js index a8d6d26d1..aeb8444a6 100644 --- a/src/lib/client_action.js +++ b/src/lib/client_action.js @@ -1,5 +1,6 @@ -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); /** * Constructs a client action factory that uses specific defaults @@ -61,7 +62,7 @@ function makeFactoryWithModifier(modifier) { return exec(this.transport, spec, _.clone(params), cb); } catch (e) { if (typeof cb === 'function') { - _.nextTick(cb, e); + utils.nextTick(cb, e); } else { var def = this.transport.defer(); def.reject(e); @@ -120,7 +121,7 @@ var castType = { )); }, duration: function (param, val, name) { - if (_.isNumeric(val) || _.isInterval(val)) { + if (utils.isNumeric(val) || utils.isInterval(val)) { return val; } else { throw new TypeError( @@ -151,7 +152,7 @@ var castType = { return (val === 'no' || val === 'off') ? false : !!val; }, number: function (param, val, name) { - if (_.isNumeric(val)) { + if (utils.isNumeric(val)) { return val * 1; } else { throw new TypeError('Invalid ' + name + ': expected a number.'); @@ -170,7 +171,7 @@ var castType = { if (typeof val === 'string') { return val; } - else if (_.isNumeric(val)) { + else if (utils.isNumeric(val)) { return '' + val; } else if (val instanceof Date) { @@ -325,7 +326,7 @@ function exec(transport, spec, params, cb) { request.ignore = _.isArray(params[key]) ? params[key] : [params[key]]; break; case 'method': - request.method = _.toUpperString(params[key]); + request.method = utils.toUpperString(params[key]); break; default: var paramSpec = spec.params[key]; diff --git a/src/lib/connection.js b/src/lib/connection.js index 93c8c38a6..200108614 100644 --- a/src/lib/connection.js +++ b/src/lib/connection.js @@ -1,6 +1,7 @@ module.exports = ConnectionAbstract; -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); var EventEmitter = require('events').EventEmitter; var Log = require('./log'); var Host = require('./host'); @@ -26,9 +27,9 @@ function ConnectionAbstract(host, config) { throw new TypeError('Invalid host'); } - _.makeBoundMethods(this); + utils.makeBoundMethods(this); } -_.inherits(ConnectionAbstract, EventEmitter); +utils.inherits(ConnectionAbstract, EventEmitter); /** * Make a request using this connection. Must be overridden by Connection classes, which can add whatever keys to diff --git a/src/lib/connection_pool.js b/src/lib/connection_pool.js index 87c6dfcb9..982d7c2d7 100644 --- a/src/lib/connection_pool.js +++ b/src/lib/connection_pool.js @@ -9,12 +9,13 @@ module.exports = ConnectionPool; -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); var Log = require('./log'); function ConnectionPool(config) { config = config || {}; - _.makeBoundMethods(this); + utils.makeBoundMethods(this); if (!config.log) { this.log = new Log(); @@ -27,16 +28,16 @@ function ConnectionPool(config) { this._config = config; // get the selector config var - this.selector = _.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); + this.selector = utils.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector); // get the connection class - this.Connection = _.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, + this.Connection = utils.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses, ConnectionPool.defaultConnectionClass); // time that connections will wait before being revived this.deadTimeout = config.hasOwnProperty('deadTimeout') ? config.deadTimeout : 60000; this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout') ? config.maxDeadTimeout : 18e5; - this.calcDeadTimeout = _.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); + this.calcDeadTimeout = utils.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential'); // a map of connections to their "id" property, used when sniffing this.index = {}; @@ -86,7 +87,7 @@ ConnectionPool.prototype.select = function (cb) { this.selector(this._conns.alive, cb); } else { try { - _.nextTick(cb, void 0, this.selector(this._conns.alive)); + utils.nextTick(cb, void 0, this.selector(this._conns.alive)); } catch (e) { cb(e); } @@ -94,7 +95,7 @@ ConnectionPool.prototype.select = function (cb) { } else if (this._timeouts.length) { this._selectDeadConnection(cb); } else { - _.nextTick(cb, void 0); + utils.nextTick(cb, void 0); } }; @@ -106,7 +107,7 @@ ConnectionPool.prototype.select = function (cb) { * @param {String} oldStatus - the connection's old status * @param {ConnectionAbstract} connection - the connection object itself */ -ConnectionPool.prototype.onStatusSet = _.handler(function (status, oldStatus, connection) { +ConnectionPool.prototype.onStatusSet = utils.handler(function (status, oldStatus, connection) { var index; var died = (status === 'dead'); @@ -200,7 +201,7 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea var ms = this.calcDeadTimeout(timeout.attempt, this.deadTimeout); timeout.id = setTimeout(timeout.revive, ms); - timeout.runAt = _.now() + ms; + timeout.runAt = utils.now() + ms; }; ConnectionPool.prototype._selectDeadConnection = function (cb) { diff --git a/src/lib/connectors/angular.js b/src/lib/connectors/angular.js index 3336c7462..836d4d1b7 100644 --- a/src/lib/connectors/angular.js +++ b/src/lib/connectors/angular.js @@ -6,7 +6,7 @@ */ module.exports = AngularConnector; -var _ = require('../utils'); +var utils = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; @@ -20,7 +20,7 @@ function AngularConnector(host, config) { }]); } -_.inherits(AngularConnector, ConnectionAbstract); +utils.inherits(AngularConnector, ConnectionAbstract); AngularConnector.prototype.request = function (params, cb) { var abort = this.$q.defer(); diff --git a/src/lib/connectors/browser_index.js b/src/lib/connectors/browser_index.js index 8553ee8da..dfe9abbbc 100644 --- a/src/lib/connectors/browser_index.js +++ b/src/lib/connectors/browser_index.js @@ -3,7 +3,7 @@ var opts = { jquery: require('./jquery'), angular: require('./angular') }; -var _ = require('../utils'); +var _ = require('lodash'); // remove modules that have been ignored by browserify _.each(opts, function (conn, name) { diff --git a/src/lib/connectors/http.js b/src/lib/connectors/http.js index 25b7f30c2..d59e15cc0 100644 --- a/src/lib/connectors/http.js +++ b/src/lib/connectors/http.js @@ -12,7 +12,8 @@ var handles = { http: require('http'), https: require('https') }; -var _ = require('../utils'); +var _ = require('lodash'); +var utils = require('../utils'); var parseUrl = require('url').parse; var qs = require('querystring'); var AgentKeepAlive = require('agentkeepalive'); @@ -47,9 +48,9 @@ function HttpConnector(host, config) { this.agent = config.createNodeAgent ? config.createNodeAgent(this, config) : this.createAgent(config); } -_.inherits(HttpConnector, ConnectionAbstract); +utils.inherits(HttpConnector, ConnectionAbstract); -HttpConnector.prototype.onStatusSet = _.handler(function (status) { +HttpConnector.prototype.onStatusSet = utils.handler(function (status) { if (status === 'closed') { var agent = this.agent; var toRemove = []; diff --git a/src/lib/connectors/jquery.js b/src/lib/connectors/jquery.js index d090e39cb..e128080ba 100644 --- a/src/lib/connectors/jquery.js +++ b/src/lib/connectors/jquery.js @@ -7,14 +7,14 @@ */ module.exports = JqueryConnector; -var _ = require('../utils'); +var utils = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; function JqueryConnector(host, config) { ConnectionAbstract.call(this, host, config); } -_.inherits(JqueryConnector, ConnectionAbstract); +utils.inherits(JqueryConnector, ConnectionAbstract); JqueryConnector.prototype.request = function (params, cb) { var ajax = { diff --git a/src/lib/connectors/xhr.js b/src/lib/connectors/xhr.js index 2b21539a6..72647ba18 100644 --- a/src/lib/connectors/xhr.js +++ b/src/lib/connectors/xhr.js @@ -7,7 +7,7 @@ module.exports = XhrConnector; /* jshint browser:true */ -var _ = require('../utils'); +var utils = require('../utils'); var ConnectionAbstract = require('../connection'); var ConnectionFault = require('../errors').ConnectionFault; var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent)); @@ -15,7 +15,7 @@ var asyncDefault = !(navigator && /PhantomJS/i.test(navigator.userAgent)); function XhrConnector(host, config) { ConnectionAbstract.call(this, host, config); } -_.inherits(XhrConnector, ConnectionAbstract); +utils.inherits(XhrConnector, ConnectionAbstract); /** * Simply returns an XHR object cross browser @@ -43,7 +43,7 @@ if (typeof XMLHttpRequest !== 'undefined') { } }) .compact() - .first(); + .head(); } if (!getXhr) { diff --git a/src/lib/errors.js b/src/lib/errors.js index 377da5772..f82817e7f 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -1,4 +1,5 @@ -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); var errors = module.exports; var canCapture = (typeof Error.captureStackTrace === 'function'); @@ -34,7 +35,7 @@ function ErrorAbstract(msg, constructor, metadata) { } } errors._Abstract = ErrorAbstract; -_.inherits(ErrorAbstract, Error); +utils.inherits(ErrorAbstract, Error); /** * Connection Error @@ -43,7 +44,7 @@ _.inherits(ErrorAbstract, Error); errors.ConnectionFault = function ConnectionFault(msg) { ErrorAbstract.call(this, msg || 'Connection Failure', errors.ConnectionFault); }; -_.inherits(errors.ConnectionFault, ErrorAbstract); +utils.inherits(errors.ConnectionFault, ErrorAbstract); /** * No Living Connections @@ -52,7 +53,7 @@ _.inherits(errors.ConnectionFault, ErrorAbstract); errors.NoConnections = function NoConnections(msg) { ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections); }; -_.inherits(errors.NoConnections, ErrorAbstract); +utils.inherits(errors.NoConnections, ErrorAbstract); /** * Generic Error @@ -61,7 +62,7 @@ _.inherits(errors.NoConnections, ErrorAbstract); errors.Generic = function Generic(msg, metadata) { ErrorAbstract.call(this, msg || 'Generic Error', errors.Generic, metadata); }; -_.inherits(errors.Generic, ErrorAbstract); +utils.inherits(errors.Generic, ErrorAbstract); /** * Request Timeout Error @@ -70,7 +71,7 @@ _.inherits(errors.Generic, ErrorAbstract); errors.RequestTimeout = function RequestTimeout(msg) { ErrorAbstract.call(this, msg || 'Request Timeout', errors.RequestTimeout); }; -_.inherits(errors.RequestTimeout, ErrorAbstract); +utils.inherits(errors.RequestTimeout, ErrorAbstract); /** @@ -80,7 +81,7 @@ _.inherits(errors.RequestTimeout, ErrorAbstract); errors.Serialization = function Serialization(msg) { ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization); }; -_.inherits(errors.Serialization, ErrorAbstract); +utils.inherits(errors.Serialization, ErrorAbstract); /** @@ -89,7 +90,7 @@ _.inherits(errors.Serialization, ErrorAbstract); errors.RequestTypeError = function RequestTypeError(feature) { ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError); }; -_.inherits(errors.RequestTypeError, ErrorAbstract); +utils.inherits(errors.RequestTypeError, ErrorAbstract); var statusCodes = [ [300, 'Multiple Choices'], @@ -141,7 +142,7 @@ _.each(statusCodes, function createStatusCodeError(tuple) { var names = tuple[1]; var allNames = [].concat(names, status); var primaryName = allNames[0]; - var className = _.studlyCase(primaryName); + var className = utils.studlyCase(primaryName); allNames = _.uniq(allNames.concat(className)); function StatusCodeError(msg, metadata) { @@ -183,7 +184,7 @@ _.each(statusCodes, function createStatusCodeError(tuple) { ErrorAbstract.call(this, msg || primaryName, StatusCodeError, metadata); return this; } - _.inherits(StatusCodeError, ErrorAbstract); + utils.inherits(StatusCodeError, ErrorAbstract); allNames.forEach(function (name) { errors[name] = StatusCodeError; diff --git a/src/lib/host.js b/src/lib/host.js index 3ccddbfbf..6482c0d4f 100644 --- a/src/lib/host.js +++ b/src/lib/host.js @@ -6,7 +6,8 @@ module.exports = Host; var url = require('url'); var qs = require('querystring'); -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); var startsWithProtocolRE = /^([a-z]+:)?\/\//; var defaultProto = 'http:'; @@ -123,7 +124,7 @@ function Host(config, globalConfig) { } // make sure that the port is a number - if (_.isNumeric(this.port)) { + if (utils.isNumeric(this.port)) { this.port = parseInt(this.port, 10); } else { this.port = 9200; diff --git a/src/lib/log.js b/src/lib/log.js index 804d601f8..c13ef5ad8 100644 --- a/src/lib/log.js +++ b/src/lib/log.js @@ -1,4 +1,5 @@ -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); var url = require('url'); var EventEmitter = require('events').EventEmitter; @@ -24,12 +25,12 @@ function Log(config) { var i; var outputs; - if (_.isArrayOfStrings(config.log)) { + if (utils.isArrayOfStrings(config.log)) { outputs = [{ levels: config.log }]; } else { - outputs = _.createArray(config.log, function (val) { + outputs = utils.createArray(config.log, function (val) { if (_.isPlainObject(val)) { return val; } @@ -50,7 +51,7 @@ function Log(config) { this.addOutput(outputs[i]); } } -_.inherits(Log, EventEmitter); +utils.inherits(Log, EventEmitter); Log.loggers = require('./loggers'); @@ -209,7 +210,7 @@ Log.prototype.addOutput = function (config) { config.levels = Log.parseLevels(config.levels || config.level || 'warning'); delete config.level; - var Logger = _.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); + var Logger = utils.funcEnum(config, 'type', Log.loggers, process.browser ? 'console' : 'stdio'); return new Logger(this, config); }; diff --git a/src/lib/logger.js b/src/lib/logger.js index 5732d7fed..07e428760 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -1,4 +1,5 @@ -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); /** * Abstract class providing common functionality to loggers @@ -9,7 +10,7 @@ function LoggerAbstract(log, config) { this.log = log; this.listeningLevels = []; - _.makeBoundMethods(this); + utils.makeBoundMethods(this); // when the log closes, remove our event listeners this.log.once('closing', this.bound.cleanUpListeners); @@ -37,7 +38,7 @@ LoggerAbstract.prototype.timestamp = function () { }; function indent(text, spaces) { - var space = _.repeat(' ', spaces || 2); + var space = utils.repeat(' ', spaces || 2); return (text || '').split(/\r?\n/).map(function (line) { return space + line; }).join('\n'); @@ -65,7 +66,7 @@ LoggerAbstract.prototype.setupListeners = function (levels) { this.listeningLevels = []; _.each(levels, _.bind(function (level) { - var fnName = 'on' + _.ucfirst(level); + var fnName = 'on' + utils.ucfirst(level); if (this.bound[fnName]) { this.listeningLevels.push(level); this.log.on(level, this.bound[fnName]); @@ -82,9 +83,9 @@ LoggerAbstract.prototype.setupListeners = function (levels) { * @private * @return {undefined} */ -LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { +LoggerAbstract.prototype.cleanUpListeners = utils.handler(function () { _.each(this.listeningLevels, _.bind(function (level) { - this.log.removeListener(level, this.bound['on' + _.ucfirst(level)]); + this.log.removeListener(level, this.bound['on' + utils.ucfirst(level)]); }, this)); }); @@ -96,7 +97,7 @@ LoggerAbstract.prototype.cleanUpListeners = _.handler(function () { * @param {Error} e - The Error object to log * @return {undefined} */ -LoggerAbstract.prototype.onError = _.handler(function (e) { +LoggerAbstract.prototype.onError = utils.handler(function (e) { this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack); }); @@ -108,7 +109,7 @@ LoggerAbstract.prototype.onError = _.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onWarning = _.handler(function (msg) { +LoggerAbstract.prototype.onWarning = utils.handler(function (msg) { this.write('WARNING', msg); }); @@ -120,7 +121,7 @@ LoggerAbstract.prototype.onWarning = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onInfo = _.handler(function (msg) { +LoggerAbstract.prototype.onInfo = utils.handler(function (msg) { this.write('INFO', msg); }); @@ -132,7 +133,7 @@ LoggerAbstract.prototype.onInfo = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onDebug = _.handler(function (msg) { +LoggerAbstract.prototype.onDebug = utils.handler(function (msg) { this.write('DEBUG', msg); }); @@ -144,7 +145,7 @@ LoggerAbstract.prototype.onDebug = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -LoggerAbstract.prototype.onTrace = _.handler(function (requestDetails) { +LoggerAbstract.prototype.onTrace = utils.handler(function (requestDetails) { this.write('TRACE', this._formatTraceMessage(requestDetails)); }); diff --git a/src/lib/loggers/console.js b/src/lib/loggers/console.js index d5ec9771f..7b268ca4a 100644 --- a/src/lib/loggers/console.js +++ b/src/lib/loggers/console.js @@ -13,7 +13,8 @@ module.exports = Console; var LoggerAbstract = require('../logger'); -var _ = require('../utils'); +var _ = require('lodash'); +var utils = require('../utils'); function Console(log, config) { LoggerAbstract.call(this, log, config); @@ -21,7 +22,7 @@ function Console(log, config) { // config/state this.color = _.has(config, 'color') ? !!config.color : true; } -_.inherits(Console, LoggerAbstract); +utils.inherits(Console, LoggerAbstract); /** * Override the LoggerAbstract's setup listeners to do a little extra setup @@ -47,7 +48,7 @@ Console.prototype.write = function (label, message, to) { * @param {Error} e - The Error object to log * @return {undefined} */ -Console.prototype.onError = _.handler(function (e) { +Console.prototype.onError = utils.handler(function (e) { var to = console.error ? 'error' : 'log'; this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to); }); @@ -60,7 +61,7 @@ Console.prototype.onError = _.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onWarning = _.handler(function (msg) { +Console.prototype.onWarning = utils.handler(function (msg) { this.write('WARNING', msg, console.warn ? 'warn' : 'log'); }); @@ -72,7 +73,7 @@ Console.prototype.onWarning = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onInfo = _.handler(function (msg) { +Console.prototype.onInfo = utils.handler(function (msg) { this.write('INFO', msg, console.info ? 'info' : 'log'); }); @@ -84,7 +85,7 @@ Console.prototype.onInfo = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Console.prototype.onDebug = _.handler(function (msg) { +Console.prototype.onDebug = utils.handler(function (msg) { this.write('DEBUG', msg, console.debug ? 'debug' : 'log'); }); /** @@ -94,6 +95,6 @@ Console.prototype.onDebug = _.handler(function (msg) { * @private * @return {undefined} */ -Console.prototype.onTrace = _.handler(function (msg) { +Console.prototype.onTrace = utils.handler(function (msg) { this.write('TRACE', this._formatTraceMessage(msg), 'log'); }); diff --git a/src/lib/loggers/file.js b/src/lib/loggers/file.js index 4b4357f96..8f3f54f8f 100755 --- a/src/lib/loggers/file.js +++ b/src/lib/loggers/file.js @@ -12,7 +12,7 @@ module.exports = File; var StreamLogger = require('./stream'); -var _ = require('../utils'); +var utils = require('../utils'); var fs = require('fs'); function File(log, config) { @@ -29,10 +29,10 @@ function File(log, config) { StreamLogger.call(this, log, config); } -_.inherits(File, StreamLogger); +utils.inherits(File, StreamLogger); -File.prototype.onProcessExit = _.handler(function () { - var toWrite = _.getUnwrittenFromStream(this.stream); +File.prototype.onProcessExit = utils.handler(function () { + var toWrite = utils.getUnwrittenFromStream(this.stream); if (toWrite) { fs.appendFileSync(this.path, toWrite); } diff --git a/src/lib/loggers/stdio.js b/src/lib/loggers/stdio.js index 1ba868d33..fe22fc791 100755 --- a/src/lib/loggers/stdio.js +++ b/src/lib/loggers/stdio.js @@ -17,7 +17,8 @@ var chalk = require('chalk'); chalk.enabled = true; var LoggerAbstract = require('../logger'); -var _ = require('../utils'); +var _ = require('lodash'); +var utils = require('../utils'); var defaultColors = { error: chalk.red.bold, @@ -36,7 +37,7 @@ function Stdio(log, config) { this.colors = _.defaults(config.colors || {}, defaultColors); } -_.inherits(Stdio, LoggerAbstract); +utils.inherits(Stdio, LoggerAbstract); /** * Sends output to a stream, does some formatting first @@ -65,7 +66,7 @@ Stdio.prototype.write = function (label, message, to, colorize) { * @param {Error} e - The Error object to log * @return {undefined} */ -Stdio.prototype.onError = _.handler(function (e) { +Stdio.prototype.onError = utils.handler(function (e) { this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack, process.stderr, this.colors.error); }); @@ -77,7 +78,7 @@ Stdio.prototype.onError = _.handler(function (e) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onWarning = _.handler(function (msg) { +Stdio.prototype.onWarning = utils.handler(function (msg) { this.write('WARNING', msg, process.stderr, this.colors.warning); }); @@ -89,7 +90,7 @@ Stdio.prototype.onWarning = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onInfo = _.handler(function (msg) { +Stdio.prototype.onInfo = utils.handler(function (msg) { this.write('INFO', msg, process.stdout, this.colors.info); }); @@ -101,7 +102,7 @@ Stdio.prototype.onInfo = _.handler(function (msg) { * @param {String} msg - The message to be logged * @return {undefined} */ -Stdio.prototype.onDebug = _.handler(function (msg) { +Stdio.prototype.onDebug = utils.handler(function (msg) { this.write('DEBUG', msg, process.stdout, this.colors.debug); }); @@ -112,6 +113,6 @@ Stdio.prototype.onDebug = _.handler(function (msg) { * @private * @return {undefined} */ -Stdio.prototype.onTrace = _.handler(function (message) { +Stdio.prototype.onTrace = utils.handler(function (message) { this.write('TRACE', this._formatTraceMessage(message), process.stdout, this.colors.trace); }); diff --git a/src/lib/loggers/stream.js b/src/lib/loggers/stream.js index 235440d15..b97a9d508 100755 --- a/src/lib/loggers/stream.js +++ b/src/lib/loggers/stream.js @@ -13,7 +13,7 @@ module.exports = Stream; var LoggerAbstract = require('../logger'); -var _ = require('../utils'); +var utils = require('../utils'); function Stream(log, config) { LoggerAbstract.call(this, log, config); @@ -26,17 +26,17 @@ function Stream(log, config) { process.once('exit', this.bound.onProcessExit); } -_.inherits(Stream, LoggerAbstract); +utils.inherits(Stream, LoggerAbstract); -Stream.prototype.cleanUpListeners = _.handler(function () { +Stream.prototype.cleanUpListeners = utils.handler(function () { process.removeListener('exit', this.bound.onProcessExit); LoggerAbstract.prototype.cleanUpListeners.call(this); }); // flush the write buffer to stderr synchronously -Stream.prototype.onProcessExit = _.handler(function () { +Stream.prototype.onProcessExit = utils.handler(function () { // process is dying, lets manually flush the buffer synchronously to stderr. - var unwritten = _.getUnwrittenFromStream(this.stream); + var unwritten = utils.getUnwrittenFromStream(this.stream); if (unwritten) { console.error('Log stream did not get to finish writing. Flushing to stderr'); console.error(unwritten); diff --git a/src/lib/loggers/tracer.js b/src/lib/loggers/tracer.js index c79b48c5e..2d1494fab 100755 --- a/src/lib/loggers/tracer.js +++ b/src/lib/loggers/tracer.js @@ -14,7 +14,8 @@ module.exports = Tracer; var StreamLogger = require('./stream'); var fs = require('fs'); -var _ = require('../utils'); +var _ = require('lodash'); +var utils = require('../utils'); var url = require('url'); function Tracer(log, config) { @@ -29,14 +30,14 @@ function Tracer(log, config) { StreamLogger.call(this, log, config); } -_.inherits(Tracer, StreamLogger); +utils.inherits(Tracer, StreamLogger); var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query']; Tracer.prototype._formatTraceMessage = function (req) { var reqUrl = _.pick(url.parse(req.url, true, false), usefulUrlFields); - var originalHost = url.format(_.pick(reqUrl, 'protocol', 'hostname', 'port')); + var originalHost = url.format(_.pick(reqUrl, ['protocol', 'hostname', 'port'])); reqUrl.port = this.curlPort; reqUrl.hostname = this.curlHost; diff --git a/src/lib/nodes_to_host.js b/src/lib/nodes_to_host.js index c87ce9041..838c89d49 100644 --- a/src/lib/nodes_to_host.js +++ b/src/lib/nodes_to_host.js @@ -1,4 +1,4 @@ -var _ = require('./utils'); +var _ = require('lodash'); var extractHostPartsRE1x = /\[(?:(.*)\/)?(.+?):(\d+)\]/; diff --git a/src/lib/serializers/angular.js b/src/lib/serializers/angular.js index 1548badc1..cba397ff9 100644 --- a/src/lib/serializers/angular.js +++ b/src/lib/serializers/angular.js @@ -1,9 +1,9 @@ /* global angular */ -var _ = require('../utils'); +var utils = require('../utils'); var JsonSerializer = require('../serializers/json'); function AngularSerializer() {} -_.inherits(AngularSerializer, JsonSerializer); +utils.inherits(AngularSerializer, JsonSerializer); // mimic the JsonSerializer's encode method, but use angular's toJson instead AngularSerializer.prototype.encode = function (val) { diff --git a/src/lib/serializers/json.js b/src/lib/serializers/json.js index 3f9f8d646..dbfb18b9b 100755 --- a/src/lib/serializers/json.js +++ b/src/lib/serializers/json.js @@ -4,7 +4,7 @@ */ module.exports = Json; -var _ = require('../utils'); +var _ = require('lodash'); function Json() {} diff --git a/src/lib/transport.js b/src/lib/transport.js index 474ca2e82..2efdb20e1 100644 --- a/src/lib/transport.js +++ b/src/lib/transport.js @@ -4,7 +4,8 @@ */ module.exports = Transport; -var _ = require('./utils'); +var _ = require('lodash'); +var utils = require('./utils'); var errors = require('./errors'); var Host = require('./host'); var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault'); @@ -18,15 +19,15 @@ function Transport(config) { config.log = self.log = new LogClass(config); // setup the connection pool - var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); + var ConnectionPool = utils.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); self.connectionPool = new ConnectionPool(config); // setup the serializer - var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json'); + var Serializer = utils.funcEnum(config, 'serializer', Transport.serializers, 'json'); self.serializer = new Serializer(config); // setup the nodesToHostCallback - self.nodesToHostCallback = _.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); + self.nodesToHostCallback = utils.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); // setup max retries self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3; @@ -49,7 +50,7 @@ function Transport(config) { } if (config.hosts) { - var hostsConfig = _.createArray(config.hosts, function (val) { + var hostsConfig = utils.createArray(config.hosts, function (val) { if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) { return val; } @@ -179,7 +180,7 @@ Transport.prototype.request = function (params, cb) { } if (body && params.method === 'GET') { - _.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); + utils.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); return ret; } @@ -292,7 +293,7 @@ Transport.prototype.request = function (params, cb) { if ( (!err || err instanceof errors.Serialization) && (status < 200 || status >= 300) - && (!params.ignore || !_.include(params.ignore, status)) + && (!params.ignore || !_.includes(params.ignore, status)) ) { var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); diff --git a/src/lib/transport/find_common_protocol.js b/src/lib/transport/find_common_protocol.js index ae1a0f536..b3843ae84 100644 --- a/src/lib/transport/find_common_protocol.js +++ b/src/lib/transport/find_common_protocol.js @@ -1,7 +1,7 @@ -var isEmpty = require('lodash.isempty'); +var _ = require('lodash'); module.exports = function (hosts) { - if (isEmpty(hosts)) return false; + if (_.isEmpty(hosts)) return false; var commonProtocol = hosts.shift().protocol; for (var i = 0; i < hosts.length; i++) { @@ -11,4 +11,4 @@ module.exports = function (hosts) { } return commonProtocol; -} +}; diff --git a/src/lib/transport/sniff_on_connection_fault.js b/src/lib/transport/sniff_on_connection_fault.js index e7bd8c089..b9d084996 100644 --- a/src/lib/transport/sniff_on_connection_fault.js +++ b/src/lib/transport/sniff_on_connection_fault.js @@ -1,4 +1,4 @@ -var _ = require('../utils'); +var utils = require('../utils'); /** @@ -25,7 +25,7 @@ module.exports = function setupSniffOnConnectionFault(transport) { // create a function that will count down to a // point n milliseconds into the future var countdownTo = function (ms) { - var start = _.now(); + var start = utils.now(); return function () { return start - ms; }; diff --git a/src/lib/utils.js b/src/lib/utils.js index 87d7c9cbd..923049c20 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -1,27 +1,15 @@ -var path = require('path'); +var _ = require('lodash'); var nodeUtils = require('util'); -var lodash = require('lodash'); /** - * Custom utils library, basically a modified version of [lodash](http://lodash.com/docs) + - * [node.utils](http://nodejs.org/api/util.html#util_util) that doesn't use mixins to prevent - * confusion when requiring lodash itself. + * Custom utils library * * @class utils * @static */ -var _ = lodash.assign({}, lodash, nodeUtils); +var utils = {}; -/** - * Link to [path.join](http://nodejs.org/api/path.html#path_path_join_path1_path2) - * - * @method _.joinPath - * @type {function} - */ -_.joinPath = path.join; - -_.get = require('lodash.get'); -_.trimEnd = require('lodash.trimend'); +utils.inherits = nodeUtils.inherits; /** * Recursively merge two objects, walking into each object and concating arrays. If both to and from have a value at a @@ -33,7 +21,7 @@ _.trimEnd = require('lodash.trimend'); * @param {Object} from - Object to pull changed from * @return {Object} - returns the modified to value */ -_.deepMerge = function (to, from) { +utils.deepMerge = function (to, from) { _.each(from, function (fromVal, key) { switch (typeof to[key]) { case 'undefined': @@ -44,7 +32,7 @@ _.deepMerge = function (to, from) { to[key] = to[key].concat(from[key]); } else if (_.isPlainObject(to[key]) && _.isPlainObject(from[key])) { - _.deepMerge(to[key], from[key]); + utils.deepMerge(to[key], from[key]); } } }); @@ -58,7 +46,7 @@ _.deepMerge = function (to, from) { * @param {Array} arr - An array to check * @return {Boolean} */ -_.isArrayOfStrings = function (arr) { +utils.isArrayOfStrings = function (arr) { // quick shallow check of arrays return _.isArray(arr) && _.every(arr.slice(0, 10), _.isString); }; @@ -71,7 +59,7 @@ _.isArrayOfStrings = function (arr) { * @param {string} word - The word to transform * @return {string} */ -_.ucfirst = function (word) { +utils.ucfirst = function (word) { return word[0].toUpperCase() + word.substring(1).toLowerCase(); }; @@ -132,7 +120,7 @@ function adjustWordCase(firstWordCap, otherWordsCap, sep) { * @param {String} string * @return {String} */ -_.studlyCase = adjustWordCase(true, true, ''); +utils.studlyCase = adjustWordCase(true, true, ''); /** * Transform a string into camelCase @@ -141,7 +129,7 @@ _.studlyCase = adjustWordCase(true, true, ''); * @param {String} string * @return {String} */ -_.camelCase = adjustWordCase(false, true, ''); +utils.camelCase = adjustWordCase(false, true, ''); /** * Transform a string into snakeCase @@ -150,24 +138,7 @@ _.camelCase = adjustWordCase(false, true, ''); * @param {String} string * @return {String} */ -_.snakeCase = adjustWordCase(false, false, '_'); - -/** - * Lower-case a string, and return an empty string if any is not a string - * - * @param any {*} - Something or nothing - * @returns {string} - */ -_.toLowerString = function (any) { - if (any) { - if (typeof any !== 'string') { - any = any.toString(); - } - } else { - any = ''; - } - return any.toLowerCase(); -}; +utils.snakeCase = adjustWordCase(false, false, '_'); /** * Upper-case the string, return an empty string if any is not a string @@ -175,7 +146,7 @@ _.toLowerString = function (any) { * @param any {*} - Something or nothing * @returns {string} */ -_.toUpperString = function (any) { +utils.toUpperString = function (any) { if (any) { if (typeof any !== 'string') { any = any.toString(); @@ -193,7 +164,7 @@ _.toUpperString = function (any) { * @param {*} val * @return {Boolean} */ -_.isNumeric = function (val) { +utils.isNumeric = function (val) { return typeof val !== 'object' && val - parseFloat(val) >= 0; }; @@ -207,7 +178,7 @@ var intervalRE = /^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/; * @param {String} val * @return {Boolean} */ -_.isInterval = function (val) { +utils.isInterval = function (val) { return !!(val.match && val.match(intervalRE)); }; @@ -220,7 +191,7 @@ _.isInterval = function (val) { * @param {Number} times - Times the string should be repeated * @return {String} */ -_.repeat = function (what, times) { +utils.repeat = function (what, times) { return (new Array(times + 1)).join(what); }; @@ -233,7 +204,7 @@ _.repeat = function (what, times) { * @param [sliceIndex=0] {Integer} - The index that args should be sliced at, before feeding args to func * @returns {*} - the return value of func */ -_.applyArgs = function (func, context, args, sliceIndex) { +utils.applyArgs = function (func, context, args, sliceIndex) { sliceIndex = sliceIndex || 0; switch (args.length - sliceIndex) { case 0: @@ -259,9 +230,9 @@ _.applyArgs = function (func, context, args, sliceIndex) { * when it is called. * @return {[type]} [description] */ -_.nextTick = function (cb) { +utils.nextTick = function (cb) { // bind the function and schedule it - process.nextTick(_.bindKey(_, 'applyArgs', cb, null, arguments, 1)); + process.nextTick(_.bindKey(utils, 'applyArgs', cb, null, arguments, 1)); }; /** @@ -269,21 +240,19 @@ _.nextTick = function (cb) { * flagging it to be bound to the object at object creation when "makeBoundMethods" is called * * ``` - * ClassName.prototype.methodName = _.handler(function () { + * ClassName.prototype.methodName = utils.handler(function () { * // this will always be bound when called via classInstance.bound.methodName * this === classInstance * }); * ``` * - * @alias _.scheduled * @param {Function} func - The method that is being defined * @return {Function} */ -_.handler = function (func) { +utils.handler = function (func) { func._provideBound = true; return func; }; -_.scheduled = _.handler; /** * Creates an "bound" property on an object, which all or a subset of methods from @@ -294,14 +263,14 @@ _.scheduled = _.handler; * onEvent: function () {} * }; * - * _.makeBoundMethods(obj); + * utils.makeBoundMethods(obj); * * obj.bound.onEvent() // is bound to obj, and can safely be used as an event handler. * ``` * * @param {Object} obj - The object to bind the methods to */ -_.makeBoundMethods = function (obj) { +utils.makeBoundMethods = function (obj) { obj.bound = {}; for (var prop in obj) { // dearest maintainer, we want to look through the prototype @@ -311,15 +280,13 @@ _.makeBoundMethods = function (obj) { } }; -_.noop = function () {}; - /** * Implements the standard "string or constructor" check that I was copy/pasting everywhere * @param {String|Function} val - the value that the user passed in * @param {Object} opts - a map of the options * @return {Function|undefined} - If a valid option was specified, then the constructor is returned */ -_.funcEnum = function (config, name, opts, def) { +utils.funcEnum = function (config, name, opts, def) { var val = config[name]; switch (typeof val) { case 'undefined': @@ -357,7 +324,7 @@ _.funcEnum = function (config, name, opts, def) { * @param {Function} transform - A function called for each element of the resulting array * @return {Array|false} - an array on success, or false on failure. */ -_.createArray = function (input, transform) { +utils.createArray = function (input, transform) { transform = typeof transform === 'function' ? transform : _.identity; var output = []; var item; @@ -386,8 +353,8 @@ _.createArray = function (input, transform) { * @param {WritableStream} stream - an instance of stream.Writable * @return {string} - the remaining test to be written to the stream */ -_.getUnwrittenFromStream = function (stream) { - var writeBuffer = _.getStreamWriteBuffer(stream); +utils.getUnwrittenFromStream = function (stream) { + var writeBuffer = utils.getStreamWriteBuffer(stream); if (!writeBuffer) return; // flush the write buffer @@ -408,7 +375,7 @@ _.getUnwrittenFromStream = function (stream) { return out; }; -_.getStreamWriteBuffer = function (stream) { +utils.getStreamWriteBuffer = function (stream) { if (!stream || !stream._writableState) return; var writeState = stream._writableState; @@ -420,16 +387,16 @@ _.getStreamWriteBuffer = function (stream) { } }; -_.clearWriteStreamBuffer = function (stream) { - var buffer = _.getStreamWriteBuffer(stream); +utils.clearWriteStreamBuffer = function (stream) { + var buffer = utils.getStreamWriteBuffer(stream); return buffer && buffer.splice(0); }; /** * return the current time in milliseconds since epoch */ -_.now = function () { +utils.now = function () { return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime(); }; -module.exports = _; +module.exports = utils; diff --git a/test/fixtures/keepalive.js b/test/fixtures/keepalive.js index 63c30c9b1..abbdee2d7 100644 --- a/test/fixtures/keepalive.js +++ b/test/fixtures/keepalive.js @@ -24,7 +24,7 @@ process.once('message', function (port) { .transform(function (sockets, conn) { sockets.push(_.values(conn.agent.sockets), _.values(conn.agent.freeSockets)); }, []) - .flatten() + .flattenDeep() .value(); es.close(); diff --git a/test/integration/yaml_suite/client_manager.js b/test/integration/yaml_suite/client_manager.js index 372a7b427..0a7c1869c 100644 --- a/test/integration/yaml_suite/client_manager.js +++ b/test/integration/yaml_suite/client_manager.js @@ -9,7 +9,7 @@ if (BROWSER) { es = require('../../../src/elasticsearch'); } -var _ = require('../../../src/lib/utils'); +var _ = require('lodash'); var path = require('path'); var fs = require('fs'); var fromRoot = _.bindKey(path, 'join', require('find-root')(__dirname)); @@ -130,7 +130,7 @@ module.exports = { ]); }; - _.nextTick(cb); + process.nextTick(cb); } }, get: function () { diff --git a/test/integration/yaml_suite/run.js b/test/integration/yaml_suite/run.js index 9ec43a994..64184700c 100644 --- a/test/integration/yaml_suite/run.js +++ b/test/integration/yaml_suite/run.js @@ -4,8 +4,9 @@ module.exports = function (branch) { var YamlFile = require('./yaml_file'); var root = require('find-root')(__dirname); var rootReq = function (loc) { return require(path.join(root, loc)); }; - var _ = rootReq('src/lib/utils'); - var utils = rootReq('grunt/utils'); + var _ = require('lodash'); + var utils = rootReq('src/lib/utils'); + var gruntUtils = rootReq('grunt/utils'); var es = rootReq('src/elasticsearch'); var clientManager = require('./client_manager'); @@ -32,7 +33,7 @@ module.exports = function (branch) { return clientManager.get().clearEs(); }); - var files = _.map(require('./yaml_tests_' + _.snakeCase(branch) + '.json'), function (docs, filename) { + var files = _.map(require('./yaml_tests_' + utils.snakeCase(branch) + '.json'), function (docs, filename) { return new YamlFile(filename, docs); }); diff --git a/test/integration/yaml_suite/yaml_file.js b/test/integration/yaml_suite/yaml_file.js index b96529fc6..db776c463 100644 --- a/test/integration/yaml_suite/yaml_file.js +++ b/test/integration/yaml_suite/yaml_file.js @@ -8,7 +8,7 @@ module.exports = YamlFile; var YamlDoc = require('./yaml_doc'); var clientManager = require('./client_manager'); -var _ = require('../../../src/lib/utils'); +var _ = require('lodash'); var async = require('async'); function YamlFile(filename, docs) { diff --git a/test/mocks/browser_http.js b/test/mocks/browser_http.js index 9b42d48ff..d726dd287 100644 --- a/test/mocks/browser_http.js +++ b/test/mocks/browser_http.js @@ -227,7 +227,7 @@ MockHttpRequest.prototype = { } //TODO title case header r += header + ': ' + this.responseHeaders[header] + '\r\n'; - }, this); + }.bind(this)); return r; }, @@ -355,7 +355,7 @@ MockHttpRequest.prototype = { this.error = true; _.each(this.requestHeaders, function (header) { delete this.requestHeaders[header]; - }, this); + }.bind(this)); this.readyState = this.DONE; if (!this.async) { diff --git a/test/unit/specs/connection_pool.js b/test/unit/specs/connection_pool.js index 0b4c8b5c3..ed6205259 100644 --- a/test/unit/specs/connection_pool.js +++ b/test/unit/specs/connection_pool.js @@ -248,12 +248,12 @@ describe('Connection Pool', function () { connection.setStatus('dead'); expect(_.size(clock.timers)).to.eql(1); - var id = _(clock.timers).keys().first(); + var id = _(clock.timers).keys().head(); // it re-dies connection.setStatus('dead'); expect(_.size(clock.timers)).to.eql(1); - expect(_(clock.timers).keys().first()).to.not.eql(id); + expect(_(clock.timers).keys().head()).to.not.eql(id); }); it('does nothing when a connection is re-alive', function () { diff --git a/test/unit/specs/file_logger.js b/test/unit/specs/file_logger.js index 4766cae6b..737b54ca6 100644 --- a/test/unit/specs/file_logger.js +++ b/test/unit/specs/file_logger.js @@ -2,7 +2,8 @@ describe('File Logger', function () { var Log = require('../../../src/lib/log'); var FileLogger = require('../../../src/lib/loggers/file'); var once = require('events').EventEmitter.prototype.once; - var _ = require('../../../src/lib/utils'); + var _ = require('lodash'); + var utils = require('../../../src/lib/utils'); var parentLog; var logger; var expect = require('expect.js'); @@ -15,7 +16,7 @@ describe('File Logger', function () { afterEach(function () { parentLog.close(); - logger && _.clearWriteStreamBuffer(logger.stream); + logger && utils.clearWriteStreamBuffer(logger.stream); }); function makeLogger(parent, levels) { diff --git a/test/unit/specs/stream_logger.js b/test/unit/specs/stream_logger.js index f4c3d65ce..03fb2ceeb 100644 --- a/test/unit/specs/stream_logger.js +++ b/test/unit/specs/stream_logger.js @@ -4,7 +4,8 @@ describe('Stream Logger', function () { var MockWritableStream = require('../../mocks/writable_stream'); var once = require('events').EventEmitter.prototype.once; var stream = new MockWritableStream(); - var _ = require('../../../src/lib/utils'); + var _ = require('lodash'); + var utils = require('../../../src/lib/utils'); var expect = require('expect.js'); var parentLog; @@ -19,7 +20,7 @@ describe('Stream Logger', function () { afterEach(function () { parentLog.close(); - _.clearWriteStreamBuffer(stream); + utils.clearWriteStreamBuffer(stream); }); function makeLogger(parent, levels) { diff --git a/test/unit/specs/transport.js b/test/unit/specs/transport.js index d3a578056..0166e36d5 100644 --- a/test/unit/specs/transport.js +++ b/test/unit/specs/transport.js @@ -285,7 +285,6 @@ describe('Transport Class', function () { describe('randomizeHosts options', function () { it('calls _.shuffle be default', function () { - var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); stub(_, 'shuffle'); var trans = new Transport({ @@ -295,7 +294,6 @@ describe('Transport Class', function () { expect(_.shuffle.callCount).to.eql(1); }); it('skips the call to _.shuffle when false', function () { - var _ = require('../../../src/lib/utils'); stub(Transport.connectionPools.main.prototype, 'setHosts'); stub(_, 'shuffle'); var trans = new Transport({ diff --git a/test/unit/specs/utils.js b/test/unit/specs/utils.js index 68f850b48..7d58e4873 100644 --- a/test/unit/specs/utils.js +++ b/test/unit/specs/utils.js @@ -1,4 +1,5 @@ -var _ = require('../../../src/lib/utils'); +var _ = require('lodash'); +var utils = require('../../../src/lib/utils'); var expect = require('expect.js'); var stub = require('../../utils/auto_release_stub').make(); @@ -13,59 +14,59 @@ describe('Utils', function () { }; it('likes arrays of strings', function () { - expect(_.isArrayOfStrings(thing.is)).to.be(true); + expect(utils.isArrayOfStrings(thing.is)).to.be(true); }); it('dislikes when there is even one non string', function () { // notice a string in the array thing.is.push(thing.not || ' not '); - expect(_.isArrayOfStrings(thing.is)).to.be(false); + expect(utils.isArrayOfStrings(thing.is)).to.be(false); }); }); describe('#isNumeric', function () { it('likes integer literals', function () { - expect(_.isNumeric('-10')).to.be(true); - expect(_.isNumeric('0')).to.be(true); - expect(_.isNumeric('5')).to.be(true); - expect(_.isNumeric(-16)).to.be(true); - expect(_.isNumeric(0)).to.be(true); - expect(_.isNumeric(32)).to.be(true); - expect(_.isNumeric('040')).to.be(true); - expect(_.isNumeric('0xFF')).to.be(true); - expect(_.isNumeric(0xFFF)).to.be(true); + expect(utils.isNumeric('-10')).to.be(true); + expect(utils.isNumeric('0')).to.be(true); + expect(utils.isNumeric('5')).to.be(true); + expect(utils.isNumeric(-16)).to.be(true); + expect(utils.isNumeric(0)).to.be(true); + expect(utils.isNumeric(32)).to.be(true); + expect(utils.isNumeric('040')).to.be(true); + expect(utils.isNumeric('0xFF')).to.be(true); + expect(utils.isNumeric(0xFFF)).to.be(true); }); it('likes float literals', function () { - expect(_.isNumeric('-1.6')).to.be(true); - expect(_.isNumeric('4.536')).to.be(true); - expect(_.isNumeric(-2.6)).to.be(true); - expect(_.isNumeric(3.1415)).to.be(true); - expect(_.isNumeric(8e5)).to.be(true); - expect(_.isNumeric('123e-2')).to.be(true); + expect(utils.isNumeric('-1.6')).to.be(true); + expect(utils.isNumeric('4.536')).to.be(true); + expect(utils.isNumeric(-2.6)).to.be(true); + expect(utils.isNumeric(3.1415)).to.be(true); + expect(utils.isNumeric(8e5)).to.be(true); + expect(utils.isNumeric('123e-2')).to.be(true); }); it('dislikes non-numeric stuff', function () { - expect(_.isNumeric('')).to.be(false); - expect(_.isNumeric(' ')).to.be(false); - expect(_.isNumeric('\t\t')).to.be(false); - expect(_.isNumeric('abcdefghijklm1234567890')).to.be(false); - expect(_.isNumeric('xabcdefx')).to.be(false); - expect(_.isNumeric(true)).to.be(false); - expect(_.isNumeric(false)).to.be(false); - expect(_.isNumeric('bcfed5.2')).to.be(false); - expect(_.isNumeric('7.2acdgs')).to.be(false); - expect(_.isNumeric(undefined)).to.be(false); - expect(_.isNumeric(null)).to.be(false); - expect(_.isNumeric(NaN)).to.be(false); - expect(_.isNumeric(Infinity)).to.be(false); - expect(_.isNumeric(Number.POSITIVE_INFINITY)).to.be(false); - expect(_.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false); - expect(_.isNumeric(new Date(2009, 1, 1))).to.be(false); - expect(_.isNumeric([])).to.be(false); - expect(_.isNumeric([1, 2, 3, 4])).to.be(false); - expect(_.isNumeric({})).to.be(false); - expect(_.isNumeric(function () {})).to.be(false); + expect(utils.isNumeric('')).to.be(false); + expect(utils.isNumeric(' ')).to.be(false); + expect(utils.isNumeric('\t\t')).to.be(false); + expect(utils.isNumeric('abcdefghijklm1234567890')).to.be(false); + expect(utils.isNumeric('xabcdefx')).to.be(false); + expect(utils.isNumeric(true)).to.be(false); + expect(utils.isNumeric(false)).to.be(false); + expect(utils.isNumeric('bcfed5.2')).to.be(false); + expect(utils.isNumeric('7.2acdgs')).to.be(false); + expect(utils.isNumeric(undefined)).to.be(false); + expect(utils.isNumeric(null)).to.be(false); + expect(utils.isNumeric(NaN)).to.be(false); + expect(utils.isNumeric(Infinity)).to.be(false); + expect(utils.isNumeric(Number.POSITIVE_INFINITY)).to.be(false); + expect(utils.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false); + expect(utils.isNumeric(new Date(2009, 1, 1))).to.be(false); + expect(utils.isNumeric([])).to.be(false); + expect(utils.isNumeric([1, 2, 3, 4])).to.be(false); + expect(utils.isNumeric({})).to.be(false); + expect(utils.isNumeric(function () {})).to.be(false); }); }); @@ -82,20 +83,20 @@ describe('Utils', function () { }, function (name, unit) { it('likes ' + name, function () { - expect(_.isInterval('1' + unit)).to.be(true); + expect(utils.isInterval('1' + unit)).to.be(true); }); it('likes decimal ' + name, function () { - expect(_.isInterval('1.5' + unit)).to.be(true); + expect(utils.isInterval('1.5' + unit)).to.be(true); }); }); it('dislikes more than one unit', function () { - expect(_.isInterval('1my')).to.be(false); + expect(utils.isInterval('1my')).to.be(false); }); it('dislikes spaces', function () { - expect(_.isInterval('1 m')).to.be(false); + expect(utils.isInterval('1 m')).to.be(false); }); }); }); @@ -105,108 +106,88 @@ describe('Utils', function () { describe('#camelCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); + expect(utils.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog'); }); it('ignores abreviations', function () { - expect(_.camelCase('Json_parser')).to.eql('jsonParser'); + expect(utils.camelCase('Json_parser')).to.eql('jsonParser'); }); it('handles leading _', function () { - expect(_.camelCase('_thing_one_')).to.eql('_thingOne'); + expect(utils.camelCase('_thing_one_')).to.eql('_thingOne'); }); it('works on numbers', function () { - expect(_.camelCase('version 1.0')).to.eql('version10'); + expect(utils.camelCase('version 1.0')).to.eql('version10'); }); }); describe('#studlyCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); + expect(utils.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog'); }); it('ignores abreviations', function () { - expect(_.studlyCase('Json_parser')).to.eql('JsonParser'); + expect(utils.studlyCase('Json_parser')).to.eql('JsonParser'); }); it('handles leading _', function () { - expect(_.studlyCase('_thing_one_')).to.eql('_ThingOne'); + expect(utils.studlyCase('_thing_one_')).to.eql('_ThingOne'); }); it('works on numbers', function () { - expect(_.studlyCase('version 1.0')).to.eql('Version10'); + expect(utils.studlyCase('version 1.0')).to.eql('Version10'); }); }); describe('#snakeCase', function () { it('find spaces, underscores, and other natural word breaks', function () { - expect(_.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); + expect(utils.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog'); }); it('ignores abreviations', function () { - expect(_.snakeCase('Json_parser')).to.eql('json_parser'); + expect(utils.snakeCase('Json_parser')).to.eql('json_parser'); }); it('handles leading _', function () { - expect(_.snakeCase('_thing_one_')).to.eql('_thing_one'); + expect(utils.snakeCase('_thing_one_')).to.eql('_thing_one'); }); it('works on numbers', function () { - expect(_.snakeCase('version 1.0')).to.eql('version_1_0'); - }); - }); - - describe('#toLowerString', function () { - it('transforms normal strings', function () { - expect(_.toLowerString('PASTA')).to.eql('pasta'); - }); - - it('ignores long form empty vals (null, false, undef)', function () { - expect(_.toLowerString(null)).to.eql(''); - expect(_.toLowerString(false)).to.eql(''); - expect(_.toLowerString(void 0)).to.eql(''); - }); - - it('uses the objects own toString', function () { - expect(_.toLowerString(['A', 'B'])).to.eql('a,b'); - }); - - it('sorta kinda works on objects', function () { - expect(_.toLowerString({ a: 'thing' })).to.eql('[object object]'); + expect(utils.snakeCase('version 1.0')).to.eql('version_1_0'); }); }); describe('#toUpperString', function () { it('transforms normal strings', function () { - expect(_.toUpperString('PASTA')).to.eql('PASTA'); + expect(utils.toUpperString('PASTA')).to.eql('PASTA'); }); it('ignores long form empty vals (null, false, undef)', function () { - expect(_.toUpperString(null)).to.eql(''); - expect(_.toUpperString(false)).to.eql(''); - expect(_.toUpperString(void 0)).to.eql(''); + expect(utils.toUpperString(null)).to.eql(''); + expect(utils.toUpperString(false)).to.eql(''); + expect(utils.toUpperString(void 0)).to.eql(''); }); it('uses the objects own toString', function () { - expect(_.toUpperString(['A', 'B'])).to.eql('A,B'); + expect(utils.toUpperString(['A', 'B'])).to.eql('A,B'); }); it('sorta kinda works on objects', function () { - expect(_.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); + expect(utils.toUpperString({ a: 'thing' })).to.eql('[OBJECT OBJECT]'); }); }); describe('#repeat', function () { it('repeats strings', function () { - expect(_.repeat(' ', 5)).to.eql(' '); - expect(_.repeat('foobar', 2)).to.eql('foobarfoobar'); + expect(utils.repeat(' ', 5)).to.eql(' '); + expect(utils.repeat('foobar', 2)).to.eql('foobarfoobar'); }); }); describe('#ucfirst', function () { it('only capitalized the first letter, lowercases everything else', function () { - expect(_.ucfirst('ALGER')).to.eql('Alger'); + expect(utils.ucfirst('ALGER')).to.eql('Alger'); }); }); @@ -219,14 +200,14 @@ describe('Utils', function () { var obj = { foo: 'bar' }; - expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj); + expect(utils.deepMerge(obj, { bar: 'baz' })).to.eql(obj); }); it('concats arrays', function () { var obj = { foo: ['bax', 'boz'] }; - _.deepMerge(obj, { foo: ['boop'] }); + utils.deepMerge(obj, { foo: ['boop'] }); expect(obj.foo).to.have.length(3); }); @@ -234,7 +215,7 @@ describe('Utils', function () { var obj = { foo: ['stop', 'foo', 'stahp'] }; - _.deepMerge(obj, { foo: 'string' }); + utils.deepMerge(obj, { foo: 'string' }); expect(obj.foo).to.have.length(3); }); @@ -245,7 +226,7 @@ describe('Utils', function () { foo: ['bax', 'boz'] } }; - _.deepMerge(obj, { bax: { foo: ['poo'] } }); + utils.deepMerge(obj, { bax: { foo: ['poo'] } }); expect(obj.bax.foo).to.have.length(3); }); @@ -254,25 +235,25 @@ describe('Utils', function () { describe('#createArray', function () { it('accepts an array of things and simply returns a copy of it', function () { var inp = [{ a: 1 }, 'pizza']; - var out = _.createArray(inp); + var out = utils.createArray(inp); expect(out).to.eql(inp); expect(out).to.not.be(inp); }); it('accepts a primitive value and calls the the transform function', function (done) { - _.createArray('str', function (val) { + utils.createArray('str', function (val) { expect(val).to.be('str'); done(); }); }); it('wraps any non-array in an array', function () { - expect(_.createArray({})).to.eql([{}]); - expect(_.createArray('')).to.eql(['']); - expect(_.createArray(123)).to.eql([123]); - expect(_.createArray(/abc/)).to.eql([/abc/]); - expect(_.createArray(false)).to.eql([false]); + expect(utils.createArray({})).to.eql([{}]); + expect(utils.createArray('')).to.eql(['']); + expect(utils.createArray(123)).to.eql([123]); + expect(utils.createArray(/abc/)).to.eql([/abc/]); + expect(utils.createArray(false)).to.eql([false]); }); it('returns false when the transform function returns undefined', function () { - expect(_.createArray(['str', 1], function (val) { + expect(utils.createArray(['str', 1], function (val) { if (_.isString(val)) { return { val: val @@ -290,21 +271,21 @@ describe('Utils', function () { var config = { func: function () {} }; - expect(_.funcEnum(config, 'func', {}, 'toString')) + expect(utils.funcEnum(config, 'func', {}, 'toString')) .to.be(config.func); }); it('tests if the value at key in object is undefined, returns the option at key default if so', function () { var config = { func: undefined }; - expect(_.funcEnum(config, 'func', {}, 'toString')) + expect(utils.funcEnum(config, 'func', {}, 'toString')) .to.be(Object.prototype.toString); }); it('tests if the value at key in object is a string, returns the option at that key if so', function () { var config = { 'config key name': 'toString' }; - expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) + expect(utils.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON')) .to.be('pizza'); }); it('throws an informative error if the selection if invalid', function () { @@ -313,15 +294,15 @@ describe('Utils', function () { }; expect(function () { - _.funcEnum(config, 'config', {}); + utils.funcEnum(config, 'config', {}); }).to.throwError(/expected a function/i); expect(function () { - _.funcEnum(config, 'config', { main: 'default' }, 'main'); + utils.funcEnum(config, 'config', { main: 'default' }, 'main'); }).to.throwError(/expected a function or main/i); expect(function () { - _.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); + utils.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); }).to.throwError(/expected a function or one of main, other/i); }); }); @@ -337,7 +318,7 @@ describe('Utils', function () { stub(func, method); var args = _.map(new Array(i), function (val, i) { return i; }); - _.applyArgs(func, null, args); + utils.applyArgs(func, null, args); expect(func[method].callCount).to.eql(1); if (method === 'apply') { @@ -354,7 +335,7 @@ describe('Utils', function () { var args = _.map(new Array(argCount), function (val, i) { return i; }); var expected = args.slice(slice); - _.applyArgs(func, null, args, slice); + utils.applyArgs(func, null, args, slice); expect(func[method].callCount).to.eql(1); if (method === 'apply') { @@ -368,24 +349,24 @@ describe('Utils', function () { describe('#getUnwrittenFromStream', function () { it('ignores things that do not have writableState', function () { - expect(_.getUnwrittenFromStream()).to.be(undefined); - expect(_.getUnwrittenFromStream(false)).to.be(undefined); - expect(_.getUnwrittenFromStream([])).to.be(undefined); - expect(_.getUnwrittenFromStream({})).to.be(undefined); + expect(utils.getUnwrittenFromStream()).to.be(undefined); + expect(utils.getUnwrittenFromStream(false)).to.be(undefined); + expect(utils.getUnwrittenFromStream([])).to.be(undefined); + expect(utils.getUnwrittenFromStream({})).to.be(undefined); }); if (require('stream').Writable) { var MockWritableStream = require('../../mocks/writable_stream'); it('ignores empty stream', function () { var stream = new MockWritableStream(); - expect(_.getUnwrittenFromStream(stream)).to.be(''); + expect(utils.getUnwrittenFromStream(stream)).to.be(''); }); it('returns only what is in the buffer', function () { var stream = new MockWritableStream(); stream.write('hot'); stream.write('dog'); - expect(_.getUnwrittenFromStream(stream)).to.be('dog'); + expect(utils.getUnwrittenFromStream(stream)).to.be('dog'); }); } });