Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

elasticsearch

Package Overview
Dependencies
Maintainers
3
Versions
128
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

elasticsearch - npm Package Compare versions

Comparing version 16.2.0 to 16.3.0

.editorconfig

45

package.json

@@ -10,3 +10,3 @@ {

"homepage": "https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/index.html",
"version": "16.2.0",
"version": "16.3.0",
"keywords": [

@@ -21,3 +21,3 @@ "elasticsearch",

"grunt": "grunt",
"lint": "eslint ."
"lint": "node scripts/eslint"
},

@@ -51,5 +51,6 @@ "browser": {

"@babel/preset-env": "^7.0.0-beta.41",
"@spalger/eslint-config-personal": "^0.4.0",
"acorn": "^6.2.0",
"aliasify": "^2.1.0",
"async": "~0.8.0",
"aws-sdk": "2.489.0",
"babel-eslint": "^8.2.2",

@@ -61,13 +62,14 @@ "babel-loader": "^8.0.0-beta",

"browserify": "^16.1.1",
"eslint": "^2.9.0",
"eslint-config-airbnb": "^8.0.0",
"eslint-plugin-import": "^1.6.1",
"eslint-plugin-jsx-a11y": "^1.0.4",
"eslint-plugin-react": "^5.0.1",
"eslint": "6.0.1",
"eslint-config-prettier": "6.0.0",
"eslint-config-standard": "12.0.0",
"eslint-plugin-import": "2.18.0",
"eslint-plugin-node": "9.1.0",
"eslint-plugin-prettier": "3.1.0",
"eslint-plugin-promise": "4.2.1",
"eslint-plugin-standard": "4.0.0",
"expect.js": "^0.3.1",
"express": "~3.4.7",
"fast-glob": "^3.0.4",
"find-root": "~0.1.1",
"glob": "~3.2.7",
"grunt": "^1.0.1",
"grunt-aws-s3": "^2.0.0",
"grunt-cli": "^1.2.0",

@@ -79,22 +81,11 @@ "grunt-contrib-clean": "^1.0.0",

"grunt-contrib-uglify": "^1.0.1",
"grunt-contrib-watch": "^1.0.0",
"grunt-esvm": "^3.2.8",
"grunt-mocha-cov": "^0.4.0",
"grunt-open": "~0.2.2",
"grunt-prompt": "^1.3.3",
"grunt-run": "^0.6.0",
"grunt-saucelabs": "^8.6.2",
"grunt-run": "^0.8.1",
"grunt-webpack": "^3.1.1",
"jquery": "^3.3.1",
"js-yaml": "^3.6.0",
"load-grunt-config": "^0.19.2",
"load-grunt-tasks": "^3.5.0",
"mocha": "^2.2.5",
"mocha-lcov-reporter": "0.0.1",
"mocha-screencast-reporter": "~0.1.4",
"mocha": "^6.1.4",
"moment": "^2.13.0",
"nock": "^9.2.3",
"null-loader": "^0.1.1",
"open": "0.0.5",
"optimist": "~0.6.0",
"prettier": "1.18.2",
"semver": "^4.3.6",

@@ -105,5 +96,3 @@ "sinon": "^1.17.4",

"through2-map": "~1.4.0",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.1",
"xmlbuilder": "~0.4.3"
"webpack": "^3.10.0"
},

@@ -110,0 +99,0 @@ "license": "Apache-2.0",

@@ -1,2 +0,2 @@

# elasticsearch.js 16.2.0
# elasticsearch.js 16.3.0

@@ -3,0 +3,0 @@ ---

@@ -13,10 +13,11 @@ /**

/* global angular */
angular.module('elasticsearch', [])
.factory('esFactory', ['$injector', '$q', function ($injector, $q) {
var factory = function (config) {
angular.module('elasticsearch', []).factory('esFactory', [
'$injector',
'$q',
function($injector, $q) {
var factory = function(config) {
config = config || {};
config.connectionClass = AngularConnector;
config.$injector = $injector;
config.defer = function () {
config.defer = function() {
return $q.defer();

@@ -33,2 +34,3 @@ };

return factory;
}]);
},
]);
/* global jQuery */
(function ($) {
(function($) {
process.jquery_build = true;

@@ -15,3 +15,3 @@ var es = require('./elasticsearch');

$.es = $.extend({}, es);
$.es.Client = function (config) {
$.es.Client = function(config) {
config = config || {};

@@ -22,3 +22,2 @@ config.defer = defer;

};
}(jQuery));
})(jQuery);

@@ -5,5 +5,7 @@ // In order to help people who were accidentally upgraded to this ES client,

function es() {
throw new Error('Looks like you are expecting the previous "elasticsearch" module. ' +
'It is now the "es" module. To create a client with this module use ' +
'`new es.Client(params)`.');
throw new Error(
'Looks like you are expecting the previous "elasticsearch" module. ' +
'It is now the "es" module. To create a client with this module use ' +
'`new es.Client(params)`.'
);
}

@@ -10,0 +12,0 @@

@@ -1,2 +0,1 @@

var _ = require('lodash');

@@ -26,4 +25,4 @@ var utils = require('./utils');

exports.ApiNamespace = function () {};
exports.namespaceFactory = function () {
exports.ApiNamespace = function() {};
exports.namespaceFactory = function() {
function ClientNamespace(transport, client) {

@@ -42,3 +41,3 @@ this.transport = transport;

var factory = function (spec) {
var factory = function(spec) {
spec = modifier(spec);

@@ -81,4 +80,4 @@

factory.proxy = function (fn, spec) {
return function (params, cb) {
factory.proxy = function(fn, spec) {
return function(params, cb) {
if (typeof params === 'function') {

@@ -104,3 +103,3 @@ cb = params;

var castType = {
'enum': function validSelection(param, val, name) {
enum: function validSelection(param, val, name) {
if (_.isString(val) && val.indexOf(',') > -1) {

@@ -111,5 +110,7 @@ val = commaSepList(val);

if (_.isArray(val)) {
return val.map(function (v) {
return validSelection(param, v, name);
}).join(',');
return val
.map(function(v) {
return validSelection(param, v, name);
})
.join(',');
}

@@ -122,9 +123,12 @@

}
throw new TypeError('Invalid ' + name + ': expected ' + (
param.options.length > 1
? 'one of ' + param.options.join(',')
: param.options[0]
));
throw new TypeError(
'Invalid ' +
name +
': expected ' +
(param.options.length > 1
? 'one of ' + param.options.join(',')
: param.options[0])
);
},
duration: function (param, val, name) {
duration: function(param, val, name) {
if (utils.isNumeric(val) || utils.isInterval(val)) {

@@ -134,8 +138,10 @@ return val;

throw new TypeError(
'Invalid ' + name + ': expected a number or interval ' +
'(an integer followed by one of M, w, d, h, m, s, y or ms).'
'Invalid ' +
name +
': expected a number or interval ' +
'(an integer followed by one of M, w, d, h, m, s, y or ms).'
);
}
},
list: function (param, val, name) {
list: function(param, val, name) {
switch (typeof val) {

@@ -154,10 +160,14 @@ case 'number':

default:
throw new TypeError('Invalid ' + name + ': expected be a comma separated list, array, number or string.');
throw new TypeError(
'Invalid ' +
name +
': expected be a comma separated list, array, number or string.'
);
}
},
'boolean': function (param, val) {
boolean: function(param, val) {
val = _.isString(val) ? val.toLowerCase() : val;
return (val === 'no' || val === 'off') ? false : !!val;
return val === 'no' || val === 'off' ? false : !!val;
},
number: function (param, val, name) {
number: function(param, val, name) {
if (utils.isNumeric(val)) {

@@ -169,3 +179,3 @@ return val * 1;

},
string: function (param, val, name) {
string: function(param, val, name) {
switch (typeof val) {

@@ -179,20 +189,19 @@ case 'number':

},
time: function (param, val, name) {
time: function(param, val, name) {
if (typeof val === 'string') {
return val;
}
else if (utils.isNumeric(val)) {
} else if (utils.isNumeric(val)) {
return '' + val;
}
else if (val instanceof Date) {
} else if (val instanceof Date) {
return '' + val.getTime();
}
else {
} else {
throw new TypeError('Invalid ' + name + ': expected some sort of time.');
}
}
},
};
function resolveUrl(url, params) {
var vars = {}, i, key;
var vars = {};
var i;
var key;

@@ -206,3 +215,3 @@ if (url.req) {

for (i = 0; i < url.reqParamKeys.length; i ++) {
for (i = 0; i < url.reqParamKeys.length; i++) {
key = url.reqParamKeys[i];

@@ -215,3 +224,7 @@ if (!params.hasOwnProperty(key) || params[key] == null) {

if (castType[url.req[key].type]) {
vars[key] = castType[url.req[key].type](url.req[key], params[key], key);
vars[key] = castType[url.req[key].type](
url.req[key],
params[key],
key
);
} else {

@@ -230,7 +243,11 @@ vars[key] = params[key];

for (i = 0; i < url.optParamKeys.length; i ++) {
for (i = 0; i < url.optParamKeys.length; i++) {
key = url.optParamKeys[i];
if (params[key]) {
if (castType[url.opt[key].type] || params[key] == null) {
vars[key] = castType[url.opt[key].type](url.opt[key], params[key], key);
vars[key] = castType[url.opt[key].type](
url.opt[key],
params[key],
key
);
} else {

@@ -250,14 +267,19 @@ vars[key] = params[key];

return url.template(_.transform(vars, function (note, val, name) {
// encode each value
note[name] = encodeURIComponent(val);
// remove it from the params so that it isn't sent to the final request
delete params[name];
}, {}));
return url.template(
_.transform(
vars,
function(note, val, name) {
// encode each value
note[name] = encodeURIComponent(val);
// remove it from the params so that it isn't sent to the final request
delete params[name];
},
{}
)
);
}
function exec(transport, spec, params, cb) {
var request = {
method: spec.method
method: spec.method,
};

@@ -276,3 +298,5 @@ var query = {};

if (spec.paramAsBody.castToArray) {
params.body[spec.paramAsBody.body] = [].concat(params[spec.paramAsBody.param]);
params.body[spec.paramAsBody.body] = [].concat(
params[spec.paramAsBody.param]
);
} else {

@@ -308,3 +332,4 @@ params.body[spec.paramAsBody.body] = params[spec.paramAsBody.param];

for (i = 0; i < spec.urls.length; i++) {
if (request.path = resolveUrl(spec.urls[i], params)) {
request.path = resolveUrl(spec.urls[i], params);
if (request.path) {
break;

@@ -318,3 +343,6 @@ }

var minUrl = spec.url || spec.urls[spec.urls.length - 1];
throw new TypeError('Unable to build a path with those params. Supply at least ' + _.keys(minUrl.req).join(', '));
throw new TypeError(
'Unable to build a path with those params. Supply at least ' +
_.keys(minUrl.req).join(', ')
);
}

@@ -326,7 +354,11 @@

spec.paramKeys = _.keys(spec.params);
spec.requireParamKeys = _.transform(spec.params, function (req, param, key) {
if (param.required) {
req.push(key);
}
}, []);
spec.requireParamKeys = _.transform(
spec.params,
function(req, param, key) {
if (param.required) {
req.push(key);
}
},
[]
);
}

@@ -352,7 +384,11 @@

if (paramSpec) {
// param keys don't always match the param name, in those cases it's stored in the param def as "name"
// param keys don't always match the param name, in those cases it's stored in the param def as "name"
paramSpec.name = paramSpec.name || key;
if (params[key] != null) {
if (castType[paramSpec.type]) {
query[paramSpec.name] = castType[paramSpec.type](paramSpec, params[key], key);
query[paramSpec.name] = castType[paramSpec.type](
paramSpec,
params[key],
key
);
} else {

@@ -362,3 +398,6 @@ query[paramSpec.name] = params[key];

if (paramSpec['default'] && query[paramSpec.name] === paramSpec['default']) {
if (
paramSpec['default'] &&
query[paramSpec.name] === paramSpec['default']
) {
delete query[paramSpec.name];

@@ -374,5 +413,7 @@ }

for (i = 0; i < spec.requireParamKeys.length; i ++) {
for (i = 0; i < spec.requireParamKeys.length; i++) {
if (!query.hasOwnProperty(spec.requireParamKeys[i])) {
throw new TypeError('Missing required parameter ' + spec.requireParamKeys[i]);
throw new TypeError(
'Missing required parameter ' + spec.requireParamKeys[i]
);
}

@@ -387,5 +428,5 @@ }

function commaSepList(str) {
return str.split(',').map(function (i) {
return str.split(',').map(function(i) {
return i.trim();
});
}

@@ -38,4 +38,6 @@ /**

if (config.__reused) {
throw new Error('Do not reuse objects to configure the elasticsearch Client class: ' +
'https://github.com/elasticsearch/elasticsearch-js/issues/33');
throw new Error(
'Do not reuse objects to configure the elasticsearch Client class: ' +
'https://github.com/elasticsearch/elasticsearch-js/issues/33'
);
} else {

@@ -55,3 +57,3 @@ config.__reused = true;

this.close = function () {
this.close = function() {
this.transport.close();

@@ -62,7 +64,10 @@ };

_.each(EsApiClient.prototype, _.bind(function (Fn, prop) {
if (Fn.prototype instanceof clientAction.ApiNamespace) {
this[prop] = new Fn(this.transport, this);
}
}, this));
_.each(
EsApiClient.prototype,
_.bind(function(Fn, prop) {
if (Fn.prototype instanceof clientAction.ApiNamespace) {
this[prop] = new Fn(this.transport, this);
}
}, this)
);

@@ -72,4 +77,8 @@ delete this._namespaces;

EsApiClient.prototype = utils.funcEnum(config, 'apiVersion', Client.apis, '_default');
EsApiClient.prototype = utils.funcEnum(
config,
'apiVersion',
Client.apis,
'_default'
);
if (!config.sniffEndpoint && EsApiClient.prototype === Client.apis['0.90']) {

@@ -84,20 +93,21 @@ config.sniffEndpoint = '/_cluster/nodes';

_.each(config.plugins, function (setup) {
Constructor = setup(Constructor, config, {
apis: require('./apis'),
connectors: require('./connectors'),
loggers: require('./loggers'),
selectors: require('./selectors'),
serializers: require('./serializers'),
Client: require('./client'),
clientAction: clientAction,
Connection: require('./connection'),
ConnectionPool: require('./connection_pool'),
Errors: require('./errors'),
Host: require('./host'),
Log: require('./log'),
Logger: require('./logger'),
NodesToHost: require('./nodes_to_host'),
Transport: require('./transport')
}) || Constructor;
_.each(config.plugins, function(setup) {
Constructor =
setup(Constructor, config, {
apis: require('./apis'),
connectors: require('./connectors'),
loggers: require('./loggers'),
selectors: require('./selectors'),
serializers: require('./serializers'),
Client: require('./client'),
clientAction: clientAction,
Connection: require('./connection'),
ConnectionPool: require('./connection_pool'),
Errors: require('./errors'),
Host: require('./host'),
Log: require('./log'),
Logger: require('./logger'),
NodesToHost: require('./nodes_to_host'),
Transport: require('./transport'),
}) || Constructor;
});

@@ -104,0 +114,0 @@ }

@@ -31,12 +31,30 @@ /**

// get the selector config var
this.selector = utils.funcEnum(config, 'selector', ConnectionPool.selectors, ConnectionPool.defaultSelector);
this.selector = utils.funcEnum(
config,
'selector',
ConnectionPool.selectors,
ConnectionPool.defaultSelector
);
// get the connection class
this.Connection = utils.funcEnum(config, 'connectionClass', ConnectionPool.connectionClasses,
ConnectionPool.defaultConnectionClass);
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 = utils.funcEnum(config, 'calcDeadTimeout', ConnectionPool.calcDeadTimeoutOptions, 'exponential');
this.deadTimeout = config.hasOwnProperty('deadTimeout')
? config.deadTimeout
: 60000;
this.maxDeadTimeout = config.hasOwnProperty('maxDeadTimeout')
? config.maxDeadTimeout
: 18e5;
this.calcDeadTimeout = utils.funcEnum(
config,
'calcDeadTimeout',
ConnectionPool.calcDeadTimeoutOptions,
'exponential'
);

@@ -48,3 +66,3 @@ // a map of connections to their "id" property, used when sniffing

alive: [],
dead: []
dead: [],
};

@@ -62,3 +80,4 @@

ConnectionPool.connectionClasses = require('./connectors');
ConnectionPool.defaultConnectionClass = ConnectionPool.connectionClasses._default;
ConnectionPool.defaultConnectionClass =
ConnectionPool.connectionClasses._default;
delete ConnectionPool.connectionClasses._default;

@@ -68,8 +87,11 @@

ConnectionPool.calcDeadTimeoutOptions = {
flat: function (attempt, baseTimeout) {
flat: function(attempt, baseTimeout) {
return baseTimeout;
},
exponential: function (attempt, baseTimeout) {
return Math.min(baseTimeout * 2 * Math.pow(2, (attempt * 0.5 - 1)), this.maxDeadTimeout);
}
exponential: function(attempt, baseTimeout) {
return Math.min(
baseTimeout * 2 * Math.pow(2, attempt * 0.5 - 1),
this.maxDeadTimeout
);
},
};

@@ -88,3 +110,3 @@

*/
ConnectionPool.prototype.select = function (cb) {
ConnectionPool.prototype.select = function(cb) {
if (this._conns.alive.length) {

@@ -115,9 +137,13 @@ if (this.selector.length > 1) {

*/
ConnectionPool.prototype.onStatusSet = utils.handler(function (status, oldStatus, connection) {
ConnectionPool.prototype.onStatusSet = utils.handler(function(
status,
oldStatus,
connection
) {
var index;
var died = (status === 'dead');
var wasAlreadyDead = (died && oldStatus === 'dead');
var revived = (!died && oldStatus === 'dead');
var noChange = (oldStatus === status);
var died = status === 'dead';
var wasAlreadyDead = died && oldStatus === 'dead';
var revived = !died && oldStatus === 'dead';
var noChange = oldStatus === status;
var from = this._conns[oldStatus];

@@ -159,3 +185,3 @@ var to = this._conns[status];

*/
ConnectionPool.prototype._onConnectionRevived = function (connection) {
ConnectionPool.prototype._onConnectionRevived = function(connection) {
var timeout;

@@ -179,3 +205,6 @@ for (var i = 0; i < this._timeouts.length; i++) {

*/
ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) {
ConnectionPool.prototype._onConnectionDied = function(
connection,
alreadyWasDead
) {
var timeout;

@@ -193,5 +222,5 @@ if (alreadyWasDead) {

attempt: 0,
revive: function (cb) {
revive: function(cb) {
timeout.attempt++;
connection.ping(function (err) {
connection.ping(function(err) {
connection.setStatus(err ? 'dead' : 'alive');

@@ -202,3 +231,3 @@ if (cb && typeof cb === 'function') {

});
}
},
};

@@ -217,3 +246,3 @@ this._timeouts.push(timeout);

ConnectionPool.prototype._selectDeadConnection = function (cb) {
ConnectionPool.prototype._selectDeadConnection = function(cb) {
var orderedTimeouts = _.sortBy(this._timeouts, 'runAt');

@@ -235,3 +264,3 @@ var log = this.log;

if (timeout.conn.status === 'dead') {
timeout.revive(function (err) {
timeout.revive(function(err) {
if (err) {

@@ -262,3 +291,3 @@ log.warning('Unable to revive connection: ' + timeout.conn.id);

*/
ConnectionPool.prototype.getConnections = function (status, limit) {
ConnectionPool.prototype.getConnections = function(status, limit) {
var list;

@@ -284,3 +313,3 @@ if (status) {

*/
ConnectionPool.prototype.addConnection = function (connection) {
ConnectionPool.prototype.addConnection = function(connection) {
if (!connection.id) {

@@ -303,3 +332,3 @@ connection.id = connection.host.toString();

*/
ConnectionPool.prototype.removeConnection = function (connection) {
ConnectionPool.prototype.removeConnection = function(connection) {
if (!connection.id) {

@@ -322,3 +351,3 @@ connection.id = connection.host.toString();

*/
ConnectionPool.prototype.setHosts = function (hosts) {
ConnectionPool.prototype.setHosts = function(hosts) {
var connection;

@@ -348,4 +377,4 @@ var i;

ConnectionPool.prototype.getAllHosts = function () {
return _.values(this.index).map(function (connection) {
ConnectionPool.prototype.getAllHosts = function() {
return _.values(this.index).map(function(connection) {
return connection.host;

@@ -358,5 +387,5 @@ });

*/
ConnectionPool.prototype.close = function () {
ConnectionPool.prototype.close = function() {
this.setHosts([]);
};
ConnectionPool.prototype.empty = ConnectionPool.prototype.close;

@@ -44,7 +44,7 @@ module.exports = ConnectionAbstract;

*/
ConnectionAbstract.prototype.request = function () {
ConnectionAbstract.prototype.request = function() {
throw new Error('Connection#request must be overwritten by the Connector');
};
ConnectionAbstract.prototype.ping = function (params, cb) {
ConnectionAbstract.prototype.ping = function(params, cb) {
if (typeof params === 'function') {

@@ -66,17 +66,20 @@ cb = params;

abort = this.request(_.defaults(params || {}, {
path: '/',
method: 'HEAD'
}), function (err) {
if (aborted) {
return;
abort = this.request(
_.defaults(params || {}, {
path: '/',
method: 'HEAD',
}),
function(err) {
if (aborted) {
return;
}
clearTimeout(requestTimeoutId);
if (cb) {
cb(err);
}
}
clearTimeout(requestTimeoutId);
if (cb) {
cb(err);
}
});
);
if (requestTimeout) {
requestTimeoutId = setTimeout(function () {
requestTimeoutId = setTimeout(function() {
if (abort) {

@@ -87,3 +90,7 @@ abort();

if (cb) {
cb(new errors.RequestTimeout('Ping Timeout after ' + requestTimeout + 'ms'));
cb(
new errors.RequestTimeout(
'Ping Timeout after ' + requestTimeout + 'ms'
)
);
}

@@ -94,3 +101,3 @@ }, requestTimeout);

ConnectionAbstract.prototype.setStatus = function (status) {
ConnectionAbstract.prototype.setStatus = function(status) {
var origStatus = this.status;

@@ -97,0 +104,0 @@ this.status = status;

@@ -17,11 +17,14 @@ /**

var self = this;
config.$injector.invoke(['$http', '$q', function ($http, $q) {
self.$q = $q;
self.$http = $http;
}]);
config.$injector.invoke([
'$http',
'$q',
function($http, $q) {
self.$q = $q;
self.$http = $http;
},
]);
}
utils.inherits(AngularConnector, ConnectionAbstract);
AngularConnector.prototype.request = function (params, cb) {
AngularConnector.prototype.request = function(params, cb) {
var abort = this.$q.defer();

@@ -38,16 +41,19 @@

// not actually for timing out, that's handled by the transport
timeout: abort.promise
}).then(function (response) {
cb(null, response.data, response.status, response.headers());
}, function (err) {
if (err.status) {
cb(null, err.data, err.status, err.headers());
} else {
cb(new ConnectionFault(err.message));
timeout: abort.promise,
}).then(
function(response) {
cb(null, response.data, response.status, response.headers());
},
function(err) {
if (err.status) {
cb(null, err.data, err.status, err.headers());
} else {
cb(new ConnectionFault(err.message));
}
}
});
);
return function () {
return function() {
abort.resolve();
};
};
var opts = {
xhr: require('./xhr'),
jquery: require('./jquery'),
angular: require('./angular')
angular: require('./angular'),
};

@@ -9,3 +9,3 @@ var _ = require('lodash');

// remove modules that have been ignored by browserify
_.each(opts, function (conn, name) {
_.each(opts, function(conn, name) {
if (typeof conn !== 'function') {

@@ -12,0 +12,0 @@ delete opts[name];

@@ -13,3 +13,3 @@ /**

http: require('http'),
https: require('https')
https: require('https'),
};

@@ -23,3 +23,3 @@ var _ = require('lodash');

var zlib = require('zlib');
var INVALID_PATH_REGEX = /[^\u0021-\u00ff]/
var INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;

@@ -38,4 +38,8 @@ /**

if (!this.hand) {
throw new TypeError('Invalid protocol "' + this.host.protocol +
'", expected one of ' + _.keys(handles).join(', '));
throw new TypeError(
'Invalid protocol "' +
this.host.protocol +
'", expected one of ' +
_.keys(handles).join(', ')
);
}

@@ -50,15 +54,17 @@

keepAliveMaxFreeSockets: 256,
keepAliveFreeSocketTimeout: 60000
keepAliveFreeSocketTimeout: 60000,
});
this.agent = config.createNodeAgent ? config.createNodeAgent(this, config) : this.createAgent(config);
this.agent = config.createNodeAgent
? config.createNodeAgent(this, config)
: this.createAgent(config);
}
utils.inherits(HttpConnector, ConnectionAbstract);
HttpConnector.prototype.onStatusSet = utils.handler(function (status) {
HttpConnector.prototype.onStatusSet = utils.handler(function(status) {
if (status === 'closed') {
var agent = this.agent;
var toRemove = [];
var collectSockets = function (sockets, host) {
_.each(sockets, function (s) {
var collectSockets = function(sockets, host) {
_.each(sockets, function(s) {
if (s) toRemove.push([host, s]);

@@ -73,4 +79,5 @@ });

_.each(agent.freeSockets, collectSockets);
_.each(toRemove, function (args) {
var host = args[0], socket = args[1];
_.each(toRemove, function(args) {
var host = args[0];
var socket = args[1];
agent.removeSocket(socket, parseUrl(host));

@@ -82,3 +89,3 @@ socket.destroy();

HttpConnector.prototype.createAgent = function (config) {
HttpConnector.prototype.createAgent = function(config) {
var Agent = this.hand.Agent; // the class

@@ -98,3 +105,3 @@

HttpConnector.prototype.makeAgentConfig = function (config) {
HttpConnector.prototype.makeAgentConfig = function(config) {
var agentConfig = {

@@ -115,3 +122,3 @@ keepAlive: config.keepAlive,

HttpConnector.prototype.makeReqParams = function (params) {
HttpConnector.prototype.makeReqParams = function(params) {
params = params || {};

@@ -127,3 +134,3 @@ var host = this.host;

headers: host.getHeaders(params.headers),
agent: this.agent
agent: this.agent,
};

@@ -143,3 +150,3 @@

HttpConnector.prototype.request = function (params, cb) {
HttpConnector.prototype.request = function(params, cb) {
var incoming;

@@ -157,3 +164,3 @@ var timeoutId;

// completes, has an error, or is aborted.
var cleanUp = _.bind(function (err) {
var cleanUp = _.bind(function(err) {
clearTimeout(timeoutId);

@@ -169,3 +176,3 @@

if ((err instanceof Error) === false) {
if (err instanceof Error === false) {
err = void 0;

@@ -183,7 +190,7 @@ }

if (INVALID_PATH_REGEX.test(reqParams.path) === true) {
cb(new TypeError('ERR_UNESCAPED_CHARACTERS: ' + reqParams.path))
return function () {}
cb(new TypeError('ERR_UNESCAPED_CHARACTERS: ' + reqParams.path));
return function() {};
}
request = this.hand.request(reqParams, function (_incoming) {
request = this.hand.request(reqParams, function(_incoming) {
incoming = _incoming;

@@ -200,3 +207,3 @@ status = incoming.statusCode;

incoming.setEncoding('utf8');
incoming.on('data', function (d) {
incoming.on('data', function(d) {
response += d;

@@ -222,5 +229,5 @@ });

return function () {
return function() {
request.abort();
};
};
module.exports = {
http: require('./http'),
_default: 'http'
_default: 'http',
};

@@ -19,3 +19,3 @@ /* global jQuery: false */

JqueryConnector.prototype.request = function (params, cb) {
JqueryConnector.prototype.request = function(params, cb) {
var ajax = {

@@ -27,16 +27,17 @@ url: this.host.makeUrl(params),

headers: this.host.getHeaders(params.headers),
done: cb
done: cb,
};
var jqXHR = jQuery.ajax(ajax)
.done(function (data) {
var jqXHR = jQuery
.ajax(ajax)
.done(function(data) {
cb(null, data, jqXHR.statusCode(), {
'content-type': jqXHR.getResponseHeader('content-type')
'content-type': jqXHR.getResponseHeader('content-type'),
});
})
.fail(function (a, b, err) {
.fail(function(a, b, err) {
// if response is available, execute cb. Else throw ConnectionFault
if (a && a.responseText) {
cb(null, a.responseText, jqXHR.statusCode(), {
'content-type': jqXHR.getResponseHeader('content-type')
'content-type': jqXHR.getResponseHeader('content-type'),
});

@@ -48,5 +49,5 @@ } else {

return function () {
return function() {
jqXHR.abort();
};
};

@@ -8,4 +8,5 @@ /**

/* jshint browser:true */
/* eslint-env browser */
var _ = require('lodash');
var utils = require('../utils');

@@ -29,3 +30,3 @@ var ConnectionAbstract = require('../connection');

// rewrite the getXhr method to always return the native implementation
getXhr = function () {
getXhr = function() {
return new XMLHttpRequest();

@@ -36,15 +37,14 @@ };

getXhr = _(['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'])
.map(function (appName) {
/* jshint unused: false */
try {
var test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars
return function () {
return new window.ActiveXObject(appName);
};
} catch (e) {
return false;
}
})
.compact()
.head();
.map(function(appName) {
try {
var test = new window.ActiveXObject(appName); // eslint-disable-line no-unused-vars
return function() {
return new window.ActiveXObject(appName);
};
} catch (e) {
return false;
}
})
.compact()
.head();
}

@@ -56,3 +56,3 @@

XhrConnector.prototype.request = function (params, cb) {
XhrConnector.prototype.request = function(params, cb) {
var xhr = getXhr();

@@ -77,7 +77,9 @@ var timeoutId;

xhr.onreadystatechange = function () {
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
clearTimeout(timeoutId);
log.trace(params.method, url, params.body, xhr.responseText, xhr.status);
var err = xhr.status ? void 0 : new ConnectionFault(xhr.statusText || 'Request failed to complete.');
var err = xhr.status
? void 0
: new ConnectionFault(xhr.statusText || 'Request failed to complete.');
cb(err, xhr.responseText, xhr.status);

@@ -89,5 +91,5 @@ }

return function () {
return function() {
xhr.abort();
};
};

@@ -5,4 +5,4 @@ var _ = require('lodash');

var canCapture = (typeof Error.captureStackTrace === 'function');
var canStack = !!(new Error()).stack;
var canCapture = typeof Error.captureStackTrace === 'function';
var canStack = !!new Error().stack;

@@ -16,7 +16,5 @@ function ErrorAbstract(msg, constructor, metadata) {

Error.captureStackTrace(this, constructor);
}
else if (canStack) {
this.stack = (new Error()).stack;
}
else {
} else if (canStack) {
this.stack = new Error().stack;
} else {
this.stack = '';

@@ -28,10 +26,13 @@ }

this.toString = function () {
this.toString = function() {
return msg + ' :: ' + JSON.stringify(metadata);
};
this.toJSON = function () {
return _.assign({
msg: msg
}, metadata);
this.toJSON = function() {
return _.assign(
{
msg: msg,
},
metadata
);
};

@@ -57,3 +58,7 @@ }

errors.NoConnections = function NoConnections(msg) {
ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections);
ErrorAbstract.call(
this,
msg || 'No Living connections',
errors.NoConnections
);
};

@@ -80,3 +85,2 @@ utils.inherits(errors.NoConnections, ErrorAbstract);

/**

@@ -87,7 +91,10 @@ * Request Body could not be parsed

errors.Serialization = function Serialization(msg) {
ErrorAbstract.call(this, msg || 'Unable to parse/serialize body', errors.Serialization);
ErrorAbstract.call(
this,
msg || 'Unable to parse/serialize body',
errors.Serialization
);
};
utils.inherits(errors.Serialization, ErrorAbstract);
/**

@@ -97,3 +104,7 @@ * Thrown when a browser compatability issue is detected (cough, IE, cough)

errors.RequestTypeError = function RequestTypeError(feature) {
ErrorAbstract.call(this, 'Cross-domain AJAX requests ' + feature + ' are not supported', errors.RequestTypeError);
ErrorAbstract.call(
this,
'Cross-domain AJAX requests ' + feature + ' are not supported',
errors.RequestTypeError
);
};

@@ -144,3 +155,3 @@ utils.inherits(errors.RequestTypeError, ErrorAbstract);

[506, 'Variant Also Negotiates'],
[510, 'Not Extended']
[510, 'Not Extended'],
];

@@ -174,3 +185,3 @@

msg = [].concat(esErrObject.root_cause || []).reduce(function (memo, cause) {
msg = [].concat(esErrObject.root_cause || []).reduce(function(memo, cause) {
if (memo) memo += ' (and) ';

@@ -198,3 +209,3 @@

allNames.forEach(function (name) {
allNames.forEach(function(name) {
errors[name] = StatusCodeError;

@@ -204,20 +215,23 @@ });

function prettyPrint(data) {
const path = []
const path = [];
return (function print(v) {
if (typeof v === 'object') {
if (path.indexOf(v) > -1) return '[circular]'
path.push(v)
if (path.indexOf(v) > -1) return '[circular]';
path.push(v);
try {
return '{ ' + _.map(v, function (subv, name) {
return name + '=' + print(subv)
}).join(' & ') + ' }'
return (
'{ ' +
_.map(v, function(subv, name) {
return name + '=' + print(subv);
}).join(' & ') +
' }'
);
} finally {
path.pop()
path.pop();
}
} else {
return JSON.stringify(v)
return JSON.stringify(v);
}
}(data))
})(data);
}

@@ -21,8 +21,15 @@ /**

btoa = btoa || function (data) {
return (new Buffer(data, 'utf8')).toString('base64');
};
btoa =
btoa ||
function(data) {
return new Buffer(data, 'utf8').toString('base64');
};
var urlParseFields = [
'protocol', 'hostname', 'pathname', 'port', 'auth', 'query'
'protocol',
'hostname',
'pathname',
'port',
'auth',
'query',
];

@@ -40,3 +47,3 @@

rejectUnauthorized: false,
secureProtocol: null
secureProtocol: null,
};

@@ -48,3 +55,3 @@

http: 80,
https: 443
https: 443,
};

@@ -65,3 +72,8 @@

this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults);
this.ssl = _.defaults(
{},
config.ssl || {},
globalConfig.ssl || {},
sslDefaults
);

@@ -74,3 +86,6 @@ if (typeof config === 'string') {

var portWithPath = !portNoPath && firstColon < firstSlash;
if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) {
if (
(noSlash || portNoPath || portWithPath) &&
!startsWithProtocolRE.test(config)
) {
config = defaultProto + '//' + config;

@@ -94,3 +109,3 @@ }

// move hostname/portname to host/port semi-intelligently.
_.each(simplify, function (to) {
_.each(simplify, function(to) {
var from = to + 'name';

@@ -111,3 +126,3 @@ if (config[from] && config[to]) {

if (!config.auth && globalConfig.httpAuth) {
config.auth = globalConfig.httpAuth
config.auth = globalConfig.httpAuth;
}

@@ -121,5 +136,8 @@

_.forOwn(config, _.bind(function (val, prop) {
if (val != null) this[prop] = _.clone(val);
}, this));
_.forOwn(
config,
_.bind(function(val, prop) {
if (val != null) this[prop] = _.clone(val);
}, this)
);

@@ -154,3 +172,3 @@ // make sure the query string is parsed

Host.prototype.makeUrl = function (params) {
Host.prototype.makeUrl = function(params) {
params = params || {};

@@ -176,3 +194,10 @@ // build the port

if (this.host) {
return this.protocol + '://' + this.host + port + path + (query ? '?' + query : '');
return (
this.protocol +
'://' +
this.host +
port +
path +
(query ? '?' + query : '')
);
} else {

@@ -184,3 +209,3 @@ return path + (query ? '?' + query : '');

function objectPropertyGetter(prop, preOverride) {
return function (overrides) {
return function(overrides) {
if (preOverride) {

@@ -203,3 +228,5 @@ overrides = preOverride.call(this, overrides);

Host.prototype.getHeaders = objectPropertyGetter('headers', function (overrides) {
Host.prototype.getHeaders = objectPropertyGetter('headers', function(
overrides
) {
if (!this.suggestCompression) {

@@ -210,12 +237,12 @@ return overrides;

return _.defaults(overrides || {}, {
'Accept-Encoding': 'gzip,deflate'
'Accept-Encoding': 'gzip,deflate',
});
});
Host.prototype.getQuery = objectPropertyGetter('query', function (query) {
Host.prototype.getQuery = objectPropertyGetter('query', function(query) {
return typeof query === 'string' ? qs.parse(query) : query;
});
Host.prototype.toString = function () {
Host.prototype.toString = function() {
return this.makeUrl();
};

@@ -29,7 +29,9 @@ var _ = require('lodash');

if (utils.isArrayOfStrings(config.log)) {
outputs = [{
levels: config.log
}];
outputs = [
{
levels: config.log,
},
];
} else {
outputs = utils.createArray(config.log, function (val) {
outputs = utils.createArray(config.log, function(val) {
if (_.isPlainObject(val)) {

@@ -40,3 +42,3 @@ return val;

return {
level: val
level: val,
};

@@ -48,4 +50,6 @@ }

if (!outputs) {
throw new TypeError('Invalid logging output config. Expected either a log level, array of log levels, ' +
'a logger config object, or an array of logger config objects.');
throw new TypeError(
'Invalid logging output config. Expected either a log level, array of log levels, ' +
'a logger config object, or an array of logger config objects.'
);
}

@@ -61,6 +65,8 @@

Log.prototype.close = function () {
Log.prototype.close = function() {
this.emit('closing');
if (this.listenerCount()) {
console.error('Something is still listening for log events, but the logger is closing.'); // eslint-disable-line no-console
console.error(
'Something is still listening for log events, but the logger is closing.'
); // eslint-disable-line no-console
this.clearAllListeners();

@@ -74,15 +80,13 @@ }

Log.prototype.listenerCount = EventEmitter.prototype.listenerCount;
}
else if (EventEmitter.listenerCount) {
} else if (EventEmitter.listenerCount) {
// some versions of node expose EventEmitter::listenerCount
// which is more efficient the getting all listeners of a
// specific type
Log.prototype.listenerCount = function (event) {
Log.prototype.listenerCount = function(event) {
return EventEmitter.listenerCount(this, event);
};
}
else {
} else {
// all other versions of node expose a #listeners() method, which returns
// and array we have to count
Log.prototype.listenerCount = function (event) {
Log.prototype.listenerCount = function(event) {
return this.listeners(event).length;

@@ -143,3 +147,3 @@ };

*/
'trace'
'trace',
];

@@ -158,3 +162,3 @@

*/
Log.parseLevels = function (input) {
Log.parseLevels = function(input) {
switch (typeof input) {

@@ -176,4 +180,8 @@ case 'string':

default:
throw new TypeError('invalid logging level ' + input + '. Expected zero or more of these options: ' +
Log.levels.join(', '));
throw new TypeError(
'invalid logging level ' +
input +
'. Expected zero or more of these options: ' +
Log.levels.join(', ')
);
}

@@ -191,4 +199,4 @@ };

*/
Log.join = function (arrayish) {
return _.map(arrayish, function (item) {
Log.join = function(arrayish) {
return _.map(arrayish, function(item) {
if (_.isPlainObject(item)) {

@@ -215,3 +223,3 @@ return JSON.stringify(item, null, 2) + '\n';

*/
Log.prototype.addOutput = function (config) {
Log.prototype.addOutput = function(config) {
config = config || {};

@@ -223,3 +231,8 @@

var Logger = utils.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);

@@ -235,3 +248,3 @@ };

*/
Log.prototype.error = function (e) {
Log.prototype.error = function(e) {
if (this.listenerCount('error')) {

@@ -242,3 +255,2 @@ return this.emit('error', e instanceof Error ? e : new Error(e));

/**

@@ -251,3 +263,3 @@ * Log a warning message

*/
Log.prototype.warning = function (/* ...msg */) {
Log.prototype.warning = function(/* ...msg */) {
if (this.listenerCount('warning')) {

@@ -258,3 +270,2 @@ return this.emit('warning', Log.join(arguments));

/**

@@ -267,3 +278,3 @@ * Log useful info about what's going on

*/
Log.prototype.info = function (/* ...msg */) {
Log.prototype.info = function(/* ...msg */) {
if (this.listenerCount('info')) {

@@ -281,3 +292,3 @@ return this.emit('info', Log.join(arguments));

*/
Log.prototype.debug = function (/* ...msg */) {
Log.prototype.debug = function(/* ...msg */) {
if (this.listenerCount('debug')) {

@@ -300,9 +311,30 @@ return this.emit('debug', Log.join(arguments));

*/
Log.prototype.trace = function (method, requestUrl, body, responseBody, responseStatus) {
Log.prototype.trace = function(
method,
requestUrl,
body,
responseBody,
responseStatus
) {
if (this.listenerCount('trace')) {
return this.emit('trace', Log.normalizeTraceArgs(method, requestUrl, body, responseBody, responseStatus));
return this.emit(
'trace',
Log.normalizeTraceArgs(
method,
requestUrl,
body,
responseBody,
responseStatus
)
);
}
};
Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, responseStatus) {
Log.normalizeTraceArgs = function(
method,
requestUrl,
body,
responseBody,
responseStatus
) {
if (typeof requestUrl === 'string') {

@@ -327,3 +359,3 @@ requestUrl = url.parse(requestUrl, true, true);

status: responseStatus,
response: responseBody
response: responseBody,
};

@@ -330,0 +362,0 @@ };

@@ -30,10 +30,18 @@ var _ = require('lodash');

*/
LoggerAbstract.prototype.timestamp = function () {
LoggerAbstract.prototype.timestamp = function() {
var d = new Date();
return d.getUTCFullYear() + '-' +
padNumToTen(d.getUTCMonth() + 1) + '-' +
padNumToTen(d.getUTCDate()) + 'T' +
padNumToTen(d.getUTCHours()) + ':' +
padNumToTen(d.getUTCMinutes()) + ':' +
padNumToTen(d.getUTCSeconds()) + 'Z';
return (
d.getUTCFullYear() +
'-' +
padNumToTen(d.getUTCMonth() + 1) +
'-' +
padNumToTen(d.getUTCDate()) +
'T' +
padNumToTen(d.getUTCHours()) +
':' +
padNumToTen(d.getUTCMinutes()) +
':' +
padNumToTen(d.getUTCSeconds()) +
'Z'
);
};

@@ -43,12 +51,15 @@

var space = utils.repeat(' ', spaces || 2);
return (text || '').split(/\r?\n/).map(function (line) {
return space + line;
}).join('\n');
return (text || '')
.split(/\r?\n/)
.map(function(line) {
return space + line;
})
.join('\n');
}
LoggerAbstract.prototype.format = function (label, message) {
LoggerAbstract.prototype.format = function(label, message) {
return label + ': ' + this.timestamp() + '\n' + indent(message) + '\n\n';
};
LoggerAbstract.prototype.write = function () {
LoggerAbstract.prototype.write = function() {
throw new Error('This should be overwritten by the logger');

@@ -65,3 +76,3 @@ };

*/
LoggerAbstract.prototype.setupListeners = function (levels) {
LoggerAbstract.prototype.setupListeners = function(levels) {
this.cleanUpListeners();

@@ -71,11 +82,14 @@

_.each(levels, _.bind(function (level) {
var fnName = 'on' + utils.ucfirst(level);
if (this.bound[fnName]) {
this.listeningLevels.push(level);
this.log.on(level, this.bound[fnName]);
} else {
throw new Error('Unable to listen for level "' + level + '"');
}
}, this));
_.each(
levels,
_.bind(function(level) {
var fnName = 'on' + utils.ucfirst(level);
if (this.bound[fnName]) {
this.listeningLevels.push(level);
this.log.on(level, this.bound[fnName]);
} else {
throw new Error('Unable to listen for level "' + level + '"');
}
}, this)
);
};

@@ -90,6 +104,9 @@

*/
LoggerAbstract.prototype.cleanUpListeners = utils.handler(function () {
_.each(this.listeningLevels, _.bind(function (level) {
this.log.removeListener(level, this.bound['on' + utils.ucfirst(level)]);
}, this));
LoggerAbstract.prototype.cleanUpListeners = utils.handler(function() {
_.each(
this.listeningLevels,
_.bind(function(level) {
this.log.removeListener(level, this.bound['on' + utils.ucfirst(level)]);
}, this)
);
});

@@ -105,4 +122,4 @@

*/
LoggerAbstract.prototype.onError = utils.handler(function (e) {
this.write((e.name === 'Error' ? 'ERROR' : e.name), e.stack);
LoggerAbstract.prototype.onError = utils.handler(function(e) {
this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack);
});

@@ -118,3 +135,3 @@

*/
LoggerAbstract.prototype.onWarning = utils.handler(function (msg) {
LoggerAbstract.prototype.onWarning = utils.handler(function(msg) {
this.write('WARNING', msg);

@@ -131,3 +148,3 @@ });

*/
LoggerAbstract.prototype.onInfo = utils.handler(function (msg) {
LoggerAbstract.prototype.onInfo = utils.handler(function(msg) {
this.write('INFO', msg);

@@ -144,3 +161,3 @@ });

*/
LoggerAbstract.prototype.onDebug = utils.handler(function (msg) {
LoggerAbstract.prototype.onDebug = utils.handler(function(msg) {
this.write('DEBUG', msg);

@@ -157,12 +174,21 @@ });

*/
LoggerAbstract.prototype.onTrace = utils.handler(function (requestDetails) {
LoggerAbstract.prototype.onTrace = utils.handler(function(requestDetails) {
this.write('TRACE', this._formatTraceMessage(requestDetails));
});
LoggerAbstract.prototype._formatTraceMessage = function (req) {
return '-> ' + req.method + ' ' + req.url + '\n' +
this._prettyJson(req.body) + '\n' +
'<- ' + req.status + '\n' +
this._prettyJson(req.response);
/*
LoggerAbstract.prototype._formatTraceMessage = function(req) {
return (
'-> ' +
req.method +
' ' +
req.url +
'\n' +
this._prettyJson(req.body) +
'\n' +
'<- ' +
req.status +
'\n' +
this._prettyJson(req.response)
);
/*
-> GET https://sldfkjsdlfksjdf:9200/slsdkfjlxckvxhclks?sdlkj=sdlfkje

@@ -180,3 +206,3 @@ {

LoggerAbstract.prototype._prettyJson = function (body) {
LoggerAbstract.prototype._prettyJson = function(body) {
try {

@@ -183,0 +209,0 @@ if (typeof body === 'string') {

module.exports = {
console: require('./console')
console: require('./console'),
};

@@ -32,3 +32,3 @@ /**

*/
Console.prototype.setupListeners = function (levels) {
Console.prototype.setupListeners = function(levels) {
// call the super method

@@ -38,3 +38,3 @@ LoggerAbstract.prototype.setupListeners.call(this, levels);

Console.prototype.write = function (label, message, to) {
Console.prototype.write = function(label, message, to) {
if (console[to]) {

@@ -53,3 +53,3 @@ console[to](this.format(label, message));

*/
Console.prototype.onError = utils.handler(function (e) {
Console.prototype.onError = utils.handler(function(e) {
var to = console.error ? 'error' : 'log';

@@ -67,3 +67,3 @@ this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack || e.message, to);

*/
Console.prototype.onWarning = utils.handler(function (msg) {
Console.prototype.onWarning = utils.handler(function(msg) {
this.write('WARNING', msg, console.warn ? 'warn' : 'log');

@@ -80,3 +80,3 @@ });

*/
Console.prototype.onInfo = utils.handler(function (msg) {
Console.prototype.onInfo = utils.handler(function(msg) {
this.write('INFO', msg, console.info ? 'info' : 'log');

@@ -93,3 +93,3 @@ });

*/
Console.prototype.onDebug = utils.handler(function (msg) {
Console.prototype.onDebug = utils.handler(function(msg) {
this.write('DEBUG', msg, console.debug ? 'debug' : 'log');

@@ -104,4 +104,4 @@ });

*/
Console.prototype.onTrace = utils.handler(function (msg) {
Console.prototype.onTrace = utils.handler(function(msg) {
this.write('TRACE', this._formatTraceMessage(msg), 'log');
});

@@ -27,3 +27,3 @@ /**

flags: 'a',
encoding: 'utf8'
encoding: 'utf8',
});

@@ -35,3 +35,3 @@

File.prototype.onProcessExit = utils.handler(function () {
File.prototype.onProcessExit = utils.handler(function() {
var toWrite = utils.getUnwrittenFromStream(this.stream);

@@ -38,0 +38,0 @@ if (toWrite) {

@@ -6,3 +6,3 @@ module.exports = {

stdio: require('./stdio'),
tracer: require('./tracer')
tracer: require('./tracer'),
};

@@ -28,3 +28,3 @@ /**

debug: chalk.magenta.bold,
trace: chalk.white.bold
trace: chalk.white.bold,
};

@@ -54,3 +54,3 @@

*/
Stdio.prototype.write = function (label, message, to, colorize) {
Stdio.prototype.write = function(label, message, to, colorize) {
label = 'Elasticsearch ' + label;

@@ -71,4 +71,9 @@ if (this.color) {

*/
Stdio.prototype.onError = utils.handler(function (e) {
this.write(e.name === 'Error' ? 'ERROR' : e.name, e.stack, process.stderr, this.colors.error);
Stdio.prototype.onError = utils.handler(function(e) {
this.write(
e.name === 'Error' ? 'ERROR' : e.name,
e.stack,
process.stderr,
this.colors.error
);
});

@@ -84,3 +89,3 @@

*/
Stdio.prototype.onWarning = utils.handler(function (msg) {
Stdio.prototype.onWarning = utils.handler(function(msg) {
this.write('WARNING', msg, process.stderr, this.colors.warning);

@@ -97,3 +102,3 @@ });

*/
Stdio.prototype.onInfo = utils.handler(function (msg) {
Stdio.prototype.onInfo = utils.handler(function(msg) {
this.write('INFO', msg, process.stdout, this.colors.info);

@@ -110,3 +115,3 @@ });

*/
Stdio.prototype.onDebug = utils.handler(function (msg) {
Stdio.prototype.onDebug = utils.handler(function(msg) {
this.write('DEBUG', msg, process.stdout, this.colors.debug);

@@ -122,4 +127,9 @@ });

*/
Stdio.prototype.onTrace = utils.handler(function (message) {
this.write('TRACE', this._formatTraceMessage(message), process.stdout, this.colors.trace);
Stdio.prototype.onTrace = utils.handler(function(message) {
this.write(
'TRACE',
this._formatTraceMessage(message),
process.stdout,
this.colors.trace
);
});

@@ -31,3 +31,3 @@ /**

Stream.prototype.cleanUpListeners = utils.handler(function () {
Stream.prototype.cleanUpListeners = utils.handler(function() {
process.removeListener('exit', this.bound.onProcessExit);

@@ -38,7 +38,9 @@ LoggerAbstract.prototype.cleanUpListeners.call(this);

// flush the write buffer to stderr synchronously
Stream.prototype.onProcessExit = utils.handler(function () {
Stream.prototype.onProcessExit = utils.handler(function() {
// process is dying, lets manually flush the buffer synchronously to stderr.
var unwritten = utils.getUnwrittenFromStream(this.stream);
if (unwritten) {
console.error('Log stream did not get to finish writing. Flushing to stderr');
console.error(
'Log stream did not get to finish writing. Flushing to stderr'
);
console.error(unwritten);

@@ -48,8 +50,8 @@ }

Stream.prototype.write = function (label, message) {
Stream.prototype.write = function(label, message) {
this.stream.write(this.format(label, message), 'utf8');
};
Stream.prototype.close = function () {
Stream.prototype.close = function() {
this.stream.end();
};

@@ -25,3 +25,5 @@ /**

} else {
config.stream = fs.createWriteStream(config.path || 'elasticsearch-tracer.log');
config.stream = fs.createWriteStream(
config.path || 'elasticsearch-tracer.log'
);
}

@@ -36,8 +38,17 @@

var usefulUrlFields = ['protocol', 'slashes', 'port', 'hostname', 'pathname', 'query'];
var usefulUrlFields = [
'protocol',
'slashes',
'port',
'hostname',
'pathname',
'query',
];
Tracer.prototype._formatTraceMessage = function (req) {
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'])
);

@@ -50,4 +61,9 @@ reqUrl.port = this.curlPort;

var curlCall =
'# ' + originalHost + '\n' +
"curl '" + url.format(reqUrl).replace(/'/g, "\\'") + "' -X" + req.method.toUpperCase() +
'# ' +
originalHost +
'\n' +
"curl '" +
url.format(reqUrl).replace(/'/g, "\\'") +
"' -X" +
req.method.toUpperCase() +
(req.body ? " -d '" + this._prettyJson(req.body) + "'" : '');

@@ -58,3 +74,3 @@ /* jshint quotmark: single */

curl: curlCall,
msg: '-> ' + req.status + '\n' + req.response
msg: '-> ' + req.status + '\n' + req.response,
};

@@ -64,3 +80,3 @@ };

function comment(str) {
return _.map(str.split(/\r?\n/g), function (line) {
return _.map(str.split(/\r?\n/g), function(line) {
return '# ' + line;

@@ -70,3 +86,3 @@ }).join('\n');

Tracer.prototype.write = function (label, msg) {
Tracer.prototype.write = function(label, msg) {
var lead = comment(label + ': ' + this.timestamp()) + '\n';

@@ -76,4 +92,7 @@ if (typeof msg === 'string') {

} else {
this.stream.write(lead + msg.curl + '\n' + comment(msg.msg) + '\n\n', 'utf8');
this.stream.write(
lead + msg.curl + '\n' + comment(msg.msg) + '\n\n',
'utf8'
);
}
};

@@ -6,52 +6,59 @@ var _ = require('lodash');

function makeNodeParser(hostProp) {
return function (nodes) {
return _.transform(nodes, function (hosts, node, id) {
var address = _.get(node, hostProp)
if (!address) return;
return function(nodes) {
return _.transform(
nodes,
function(hosts, node, id) {
var address = _.get(node, hostProp);
if (!address) return;
var host = {
host: undefined,
port: undefined,
_meta: {
id: id,
name: node.name,
version: node.version
}
};
var host = {
host: undefined,
port: undefined,
_meta: {
id: id,
name: node.name,
version: node.version,
},
};
var malformedError = new Error(
'Malformed ' + hostProp + '.' +
' Got ' + JSON.stringify(address) +
' and expected it to match "{hostname?}/{ip}:{port}".'
);
var malformedError = new Error(
'Malformed ' +
hostProp +
'.' +
' Got ' +
JSON.stringify(address) +
' and expected it to match "{hostname?}/{ip}:{port}".'
);
var matches1x = extractHostPartsRE1x.exec(address);
if (matches1x) {
host.host = matches1x[1] || matches1x[2];
host.port = parseInt(matches1x[3], 10);
hosts.push(host);
return;
}
var matches1x = extractHostPartsRE1x.exec(address);
if (matches1x) {
host.host = matches1x[1] || matches1x[2];
host.port = parseInt(matches1x[3], 10);
hosts.push(host);
return;
}
if (address.indexOf('/') > -1) {
var withHostParts = address.split('/');
if (withHostParts.length !== 2) throw malformedError;
if (address.indexOf('/') > -1) {
var withHostParts = address.split('/');
if (withHostParts.length !== 2) throw malformedError;
host.host = withHostParts.shift();
address = withHostParts.shift();
}
host.host = withHostParts.shift();
address = withHostParts.shift();
}
if (address.indexOf(':') < 0) {
throw malformedError;
}
if (address.indexOf(':') < 0) {
throw malformedError;
}
var addressParts = address.split(':');
if (addressParts.length !== 2) {
throw malformedError;
}
var addressParts = address.split(':');
if (addressParts.length !== 2) {
throw malformedError;
}
host.host = host.host || addressParts[0];
host.port = parseInt(addressParts[1], 10);
hosts.push(host);
}, []);
host.host = host.host || addressParts[0];
host.port = parseInt(addressParts[1], 10);
hosts.push(host);
},
[]
);
};

@@ -58,0 +65,0 @@ }

module.exports = {
random: require('./random'),
roundRobin: require('./round_robin')
roundRobin: require('./round_robin'),
};

@@ -9,3 +9,3 @@ /**

*/
module.exports = function (connections) {
module.exports = function(connections) {
var connection = connections[0];

@@ -12,0 +12,0 @@ connections.push(connections.shift());

@@ -9,3 +9,3 @@ /* global angular */

// mimic the JsonSerializer's encode method, but use angular's toJson instead
AngularSerializer.prototype.encode = function (val) {
AngularSerializer.prototype.encode = function(val) {
switch (typeof val) {

@@ -18,3 +18,3 @@ case 'string':

default:
return;
return undefined;
}

@@ -21,0 +21,0 @@ };

module.exports = {
angular: require('./angular'),
json: require('./json')
json: require('./json'),
};

@@ -17,3 +17,3 @@ /**

*/
Json.prototype.serialize = function (val, replacer, spaces) {
Json.prototype.serialize = function(val, replacer, spaces) {
switch (typeof val) {

@@ -32,3 +32,3 @@ case 'string':

default:
return;
return undefined;
}

@@ -44,3 +44,3 @@ };

*/
Json.prototype.deserialize = function (str) {
Json.prototype.deserialize = function(str) {
if (typeof str === 'string') {

@@ -53,4 +53,5 @@ try {

Json.prototype.bulkBody = function (val) {
var body = '', i;
Json.prototype.bulkBody = function(val) {
var body = '';
var i;

@@ -65,3 +66,5 @@ if (_.isArray(val)) {

} else {
throw new TypeError('Bulk body should either be an Array of commands/string, or a String');
throw new TypeError(
'Bulk body should either be an Array of commands/string, or a String'
);
}

@@ -68,0 +71,0 @@

@@ -18,15 +18,31 @@ /**

var LogClass = (typeof config.log === 'function') ? config.log : require('./log');
var LogClass =
typeof config.log === 'function' ? config.log : require('./log');
config.log = self.log = new LogClass(config);
// setup the connection pool
var ConnectionPool = utils.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 = utils.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 = utils.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main');
self.nodesToHostCallback = utils.funcEnum(
config,
'nodesToHostCallback',
Transport.nodesToHostCallbacks,
'main'
);

@@ -37,7 +53,13 @@ // setup max retries

// setup endpoint to use for sniffing
self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint') ? config.sniffEndpoint : '/_nodes/_all/http';
self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint')
? config.sniffEndpoint
: '/_nodes/_all/http';
// setup requestTimeout default
self.requestTimeout = config.hasOwnProperty('requestTimeout') ? config.requestTimeout : 30000;
self.pingTimeout = config.hasOwnProperty('pingTimeout') ? config.pingTimeout : 3000;
self.requestTimeout = config.hasOwnProperty('requestTimeout')
? config.requestTimeout
: 30000;
self.pingTimeout = config.hasOwnProperty('pingTimeout')
? config.pingTimeout
: 3000;

@@ -49,3 +71,5 @@ if (config.hasOwnProperty('defer')) {

// randomizeHosts option
var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true;
var randomizeHosts = config.hasOwnProperty('randomizeHosts')
? !!config.randomizeHosts
: true;

@@ -57,3 +81,3 @@ if (config.host) {

if (config.hosts) {
var hostsConfig = utils.createArray(config.hosts, function (val) {
var hostsConfig = utils.createArray(config.hosts, function(val) {
if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) {

@@ -65,4 +89,6 @@ return val;

if (!hostsConfig) {
throw new TypeError('Invalid hosts config. Expected a URL, an array of urls, a host config object, ' +
'or an array of host config objects.');
throw new TypeError(
'Invalid hosts config. Expected a URL, an array of urls, a host config object, ' +
'or an array of host config objects.'
);
}

@@ -80,3 +106,4 @@

} else {
self.sniffedNodesProtocol = findCommonProtocol(self.connectionPool.getAllHosts()) || null;
self.sniffedNodesProtocol =
findCommonProtocol(self.connectionPool.getAllHosts()) || null;
}

@@ -113,3 +140,3 @@

Transport.connectionPools = {
main: require('./connection_pool')
main: require('./connection_pool'),
};

@@ -120,15 +147,15 @@

Transport.nodesToHostCallbacks = {
main: require('./nodes_to_host')
main: require('./nodes_to_host'),
};
Transport.prototype.defer = function () {
Transport.prototype.defer = function() {
if (typeof Promise === 'undefined') {
throw new Error(
'No Promise implementation found. In order for elasticsearch-js to create promises ' +
'either specify the `defer` configuration or include a global Promise shim'
)
'either specify the `defer` configuration or include a global Promise shim'
);
}
var defer = {};
defer.promise = new Promise(function (resolve, reject) {
defer.promise = new Promise(function(resolve, reject) {
defer.resolve = resolve;

@@ -157,3 +184,3 @@ defer.reject = reject;

*/
Transport.prototype.request = function (params, cb) {
Transport.prototype.request = function(params, cb) {
var self = this;

@@ -171,5 +198,7 @@ var remainingRetries = this.maxRetries;

var body = params.body;
var headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) {
headers[String(name).toLowerCase()] = val;
});
var headers = !params.headers
? {}
: _.transform(params.headers, function(headers, val, name) {
headers[String(name).toLowerCase()] = val;
});

@@ -185,3 +214,3 @@ self.log.debug('starting request', params);

ret = {
abort: abortRequest
abort: abortRequest,
};

@@ -195,3 +224,6 @@ } else {

if (body && params.method === 'GET') {
utils.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;

@@ -221,3 +253,4 @@ }

if (pingRequest) {
const requestParam = params.hasOwnProperty('requestTimeout') && params.requestTimeout;
const requestParam =
params.hasOwnProperty('requestTimeout') && params.requestTimeout;
requestTimeout = requestParam || this.pingTimeout;

@@ -231,3 +264,3 @@ }

body: body,
headers: headers
headers: headers,
};

@@ -275,4 +308,3 @@

(errMsg.length ? ' => ' : '') +
errMsg
;
errMsg;

@@ -300,3 +332,6 @@ if (remainingRetries) {

var parsedBody;
var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json'));
var isJson =
!headers ||
(headers['content-type'] &&
~headers['content-type'].indexOf('application/json'));

@@ -317,7 +352,6 @@ if (!err && body) {

if (
(!err || err instanceof errors.Serialization)
&& (status < 200 || status >= 300)
&& (!params.ignore || !_.includes(params.ignore, status))
(!err || err instanceof errors.Serialization) &&
(status < 200 || status >= 300) &&
(!params.ignore || !_.includes(params.ignore, status))
) {
var errorMetadata = _.pick(params.req, ['path', 'query', 'body']);

@@ -378,4 +412,8 @@ errorMetadata.statusCode = status;

if (requestTimeout && requestTimeout !== Infinity) {
requestTimeoutId = this._timeout(function () {
respond(new errors.RequestTimeout('Request Timeout after ' + requestTimeout + 'ms'));
requestTimeoutId = this._timeout(function() {
respond(
new errors.RequestTimeout(
'Request Timeout after ' + requestTimeout + 'ms'
)
);
abortRequest();

@@ -394,3 +432,3 @@ }, requestTimeout);

Transport.prototype._timeout = function (cb, delay) {
Transport.prototype._timeout = function(cb, delay) {
if (this.closed) return;

@@ -401,3 +439,3 @@

if ('function' !== typeof cb) {
if (typeof cb !== 'function') {
id = cb;

@@ -409,3 +447,3 @@ cb = void 0;

// set the timer
id = setTimeout(function () {
id = setTimeout(function() {
_.pull(timers, id);

@@ -435,3 +473,3 @@ cb();

*/
Transport.prototype.sniff = function (cb) {
Transport.prototype.sniff = function(cb) {
var self = this;

@@ -446,26 +484,35 @@ var nodesToHostCallback = this.nodesToHostCallback;

this.request({
path: this.sniffEndpoint,
query: { filter_path: sniffedNodesFilterPath },
method: 'GET'
}, function (err, resp, status) {
if (!err && resp && resp.nodes) {
var hostsConfigs;
this.request(
{
path: this.sniffEndpoint,
query: { filter_path: sniffedNodesFilterPath },
method: 'GET',
},
function(err, resp, status) {
if (!err && resp && resp.nodes) {
var hostsConfigs;
try {
hostsConfigs = nodesToHostCallback(resp.nodes);
} catch (e) {
log.error(new Error('Unable to convert node list from ' + self.sniffEndpoint +
' to hosts durring sniff. Encountered error:\n' + (e.stack || e.message)));
return;
}
try {
hostsConfigs = nodesToHostCallback(resp.nodes);
} catch (e) {
log.error(
new Error(
'Unable to convert node list from ' +
self.sniffEndpoint +
' to hosts durring sniff. Encountered error:\n' +
(e.stack || e.message)
)
);
return;
}
_.forEach(hostsConfigs, function (hostConfig) {
if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol;
});
_.forEach(hostsConfigs, function(hostConfig) {
if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol;
});
self.setHosts(hostsConfigs);
self.setHosts(hostsConfigs);
}
cb(err, resp, status);
}
cb(err, resp, status);
});
);
};

@@ -479,7 +526,9 @@

*/
Transport.prototype.setHosts = function (hostsConfigs) {
Transport.prototype.setHosts = function(hostsConfigs) {
var globalConfig = this._config;
this.connectionPool.setHosts(_.map(hostsConfigs, function (conf) {
return (conf instanceof Host) ? conf : new Host(conf, globalConfig);
}));
this.connectionPool.setHosts(
_.map(hostsConfigs, function(conf) {
return conf instanceof Host ? conf : new Host(conf, globalConfig);
})
);
};

@@ -491,3 +540,3 @@

*/
Transport.prototype.close = function () {
Transport.prototype.close = function() {
this.log.close();

@@ -494,0 +543,0 @@ this.closed = true;

var _ = require('lodash');
module.exports = function (hosts) {
module.exports = function(hosts) {
if (_.isEmpty(hosts)) return false;

@@ -5,0 +5,0 @@

var utils = require('../utils');
/**

@@ -20,3 +19,3 @@ * Patch the transport's connection pool to schedule a sniff after a connection fails.

// connect to a node this function will be called again by the connectionPool
var work = function () {
var work = function() {
work.timerId = transport._timeout(work.timerId);

@@ -28,5 +27,5 @@ transport.sniff();

// point n milliseconds into the future
var countdownTo = function (ms) {
var countdownTo = function(ms) {
var start = utils.now();
return function () {
return function() {
return start - ms;

@@ -37,3 +36,3 @@ };

// overwrite the function, but still call it
pool._onConnectionDied = function (connection, wasAlreadyDead) {
pool._onConnectionDied = function(connection, wasAlreadyDead) {
var ret = originalOnDied.call(pool, connection, wasAlreadyDead);

@@ -59,5 +58,5 @@

pool._onConnectionDied.restore = function () {
pool._onConnectionDied.restore = function() {
pool._onConnectionDied = originalOnDied;
};
};

@@ -21,3 +21,3 @@ var _ = require('lodash');

*/
utils.isArrayOfStrings = function (arr) {
utils.isArrayOfStrings = function(arr) {
// quick shallow check of arrays

@@ -27,3 +27,2 @@ return _.isArray(arr) && _.every(arr.slice(0, 10), _.isString);

/**

@@ -36,3 +35,3 @@ * Capitalize the first letter of a word

*/
utils.ucfirst = function (word) {
utils.ucfirst = function(word) {
return word[0].toUpperCase() + word.substring(1).toLowerCase();

@@ -47,3 +46,3 @@ };

function adjustWordCase(firstWordCap, otherWordsCap, sep) {
return function (string) {
return function(string) {
var i = 0;

@@ -72,6 +71,8 @@ var words = [];

} else {
if ((!words.length && firstWordCap) || (words.length && otherWordsCap)) {
if (
(!words.length && firstWordCap) ||
(words.length && otherWordsCap)
) {
word = c.toUpperCase();
}
else {
} else {
word = c.toLowerCase();

@@ -126,3 +127,3 @@ }

*/
utils.toUpperString = function (any) {
utils.toUpperString = function(any) {
if (any) {

@@ -145,3 +146,3 @@ if (typeof any !== 'string') {

*/
utils.isNumeric = function (val) {
utils.isNumeric = function(val) {
return typeof val !== 'object' && val - parseFloat(val) >= 0;

@@ -160,3 +161,3 @@ };

*/
utils.isInterval = function (val) {
utils.isInterval = function(val) {
return !!(val.match && val.match(intervalRE));

@@ -174,4 +175,4 @@ };

*/
utils.repeat = function (what, times) {
return (new Array(times + 1)).join(what);
utils.repeat = function(what, times) {
return new Array(times + 1).join(what);
};

@@ -188,3 +189,3 @@

*/
utils.applyArgs = function (func, context, args, sliceIndex) {
utils.applyArgs = function(func, context, args, sliceIndex) {
sliceIndex = sliceIndex || 0;

@@ -199,8 +200,25 @@ switch (args.length - sliceIndex) {

case 3:
return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex]);
return func.call(
context,
args[0 + sliceIndex],
args[1 + sliceIndex],
args[2 + sliceIndex]
);
case 4:
return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex], args[2 + sliceIndex], args[3 + sliceIndex]);
return func.call(
context,
args[0 + sliceIndex],
args[1 + sliceIndex],
args[2 + sliceIndex],
args[3 + sliceIndex]
);
case 5:
return func.call(context, args[0 + sliceIndex], args[1 + sliceIndex],
args[2 + sliceIndex], args[3 + sliceIndex], args[4 + sliceIndex]);
return func.call(
context,
args[0 + sliceIndex],
args[1 + sliceIndex],
args[2 + sliceIndex],
args[3 + sliceIndex],
args[4 + sliceIndex]
);
default:

@@ -216,3 +234,3 @@ return func.apply(context, Array.prototype.slice.call(args, sliceIndex));

*/
utils.nextTick = function (cb) {
utils.nextTick = function(cb) {
// bind the function and schedule it

@@ -236,3 +254,3 @@ process.nextTick(_.bindKey(utils, 'applyArgs', cb, null, arguments, 1));

*/
utils.handler = function (func) {
utils.handler = function(func) {
func._provideBound = true;

@@ -258,3 +276,3 @@ return func;

*/
utils.makeBoundMethods = function (obj) {
utils.makeBoundMethods = function(obj) {
obj.bound = {};

@@ -275,3 +293,3 @@ for (var prop in obj) {

*/
utils.funcEnum = function (config, name, opts, def) {
utils.funcEnum = function(config, name, opts, def) {
var val = config[name];

@@ -314,3 +332,3 @@ switch (typeof val) {

*/
utils.createArray = function (input, transform) {
utils.createArray = function(input, transform) {
transform = typeof transform === 'function' ? transform : _.identity;

@@ -344,3 +362,3 @@ var output = [];

*/
utils.getUnwrittenFromStream = function (stream) {
utils.getUnwrittenFromStream = function(stream) {
var writeBuffer = utils.getStreamWriteBuffer(stream);

@@ -353,7 +371,10 @@ if (!writeBuffer) return;

_.each(writeBuffer, function (writeReq) {
_.each(writeBuffer, function(writeReq) {
if (writeReq.chunk) {
// 0.9.12+ uses WriteReq objects with a chunk prop
out += '' + writeReq.chunk;
} else if (_.isArray(writeReq) && (typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))) {
} else if (
_.isArray(writeReq) &&
(typeof writeReq[0] === 'string' || Buffer.isBuffer(writeReq[0]))
) {
// 0.9.4 - 0.9.9 buffers are arrays of arrays like [[chunk, cb], [chunk, undef], ...].

@@ -368,3 +389,3 @@ out += '' + writeReq[0];

utils.getStreamWriteBuffer = function (stream) {
utils.getStreamWriteBuffer = function(stream) {
if (!stream || !stream._writableState) return;

@@ -381,3 +402,3 @@

utils.clearWriteStreamBuffer = function (stream) {
utils.clearWriteStreamBuffer = function(stream) {
var buffer = utils.getStreamWriteBuffer(stream);

@@ -390,6 +411,6 @@ return buffer && buffer.splice(0);

*/
utils.now = function () {
return (typeof Date.now === 'function') ? Date.now() : (new Date()).getTime();
utils.now = function() {
return typeof Date.now === 'function' ? Date.now() : new Date().getTime();
};
module.exports = utils;
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc