Compare commits

...

40 Commits

Author SHA1 Message Date
388c5e8e7e force replace a bad link in generated docs 2019-10-31 12:35:22 -07:00
a3d0999efd update changelog 2019-10-31 11:42:17 -07:00
9ad64f822a version 16.5.0 2019-10-31 11:38:30 -07:00
549996914a [apis] regenerate 2019-10-31 11:36:49 -07:00
d927f5e527 move to 7.4 api by default 2019-10-31 11:33:48 -07:00
50908d3666 fixed typo in 'Elasticsearch' (#19)
fixed typo in 'Elasticsearch'
2019-10-15 16:21:43 +02:00
4d4fe17a80 fixed typo in 'Elasticsearch' 2019-10-15 00:27:05 +02:00
1d75ddb4e6 version 16.4.0 2019-09-18 18:34:48 -07:00
f75fff6b5a [api] regenerate 2019-09-18 18:31:32 -07:00
d699640031 default to api version 7.3 2019-09-18 18:30:54 -07:00
a0dfc4ab9f [apis] regenerate 2019-09-18 18:27:54 -07:00
31e5ab8fea add support for 7.4 branch 2019-09-18 18:27:54 -07:00
c20598737d pin branches to just before elastic/elasticsearch#42346 2019-09-18 18:27:54 -07:00
51255d000c Add apiVersion to the code example (#13)
* Add apiVersion to the code example

* set the apiVersion in code example

Co-Authored-By: Tomas Della Vedova <delvedor@users.noreply.github.com>
2019-08-27 14:45:44 -07:00
8c359aeb7e add package to grunt config 2019-07-10 07:36:15 -07:00
e234705d56 version 16.3.0 2019-07-10 07:33:58 -07:00
bf7632ee02 add changelog entry for 16.2.0 2019-07-10 07:31:28 -07:00
fc59a5db3d remove unused webpack-dev-server package 2019-07-10 07:28:06 -07:00
50fdaea949 add acorn dev dep, required as a peer by a few packages 2019-07-10 07:26:37 -07:00
58a29395e2 remove packages to get npm audit to pass (#11)
* remove packages to get `npm audit` to pass

* fix grunt.config.init() call lost in split up

* remove integration tests, they don't work and nobody is running them

* fix upload_to_s3 task after refactor
2019-07-10 07:22:27 -07:00
7c1573fb07 Use standard and prettier (#10)
* switch from custom eslint config to standard + prettier

* fix new standard eslint violations

* add editorconfig file

* auto-fix all other violations

* update lint yarn script

* remove jshint comment
2019-07-09 13:24:13 -07:00
f69840c50f version 16.2.0 2019-07-03 10:26:35 -07:00
34b7c55115 [apis] regenerate 2019-07-03 10:24:22 -07:00
1eac96966c update branches for recent versions 2019-07-03 10:13:01 -07:00
2434247095 version 16.1.1 2019-06-04 08:36:15 -07:00
9e1b3a0059 Update README and links (#5)
Update README and links
2019-06-04 17:32:12 +02:00
ccdfa59842 Merge branch '16.x' into update-readme 2019-06-04 17:32:03 +02:00
cc670edd88 version 16.1.0 2019-05-29 19:13:03 -07:00
8fbcf3b6af [apis] regenerate 2019-05-29 19:11:35 -07:00
a7c33b5737 default apiVersion is now 7.1, add support for 7.2 2019-05-29 19:11:25 -07:00
35bfca75b4 Updated homepage and repository fields 2019-05-24 18:31:01 +02:00
c070cf32b1 Updated changelog url 2019-05-24 18:30:47 +02:00
9bb06c1058 Updated README.md
- Added a note about the new JS client
- Updated documentation links
2019-05-24 18:27:50 +02:00
4e0f785e89 Docs: Fix link in changelog (#797)
The changelog had a link to `/current/configuration.html` which isn't in
the current version of the docs anymore. This changes the link from a
fully qualified link to an in-book link.

(cherry picked from commit ba6912cb82)
2019-05-02 11:10:05 -07:00
027956bac1 Make legacy docs asciidoctor compatible (#793)
* Make legacy docs asciidoctor compatible

This modifies the legacy client documentation so that it is is
compatible with Asciidoctor. With these changes asciidoctor renders the
same way as asciidoc, module spacing and a couple of auto-generated ids.
I'm willing to ignore the auto-generated anchors because these are
legacy docs.

* Updated configuration template

(cherry picked from commit d699045504)
2019-05-02 11:09:51 -07:00
110d5f42e5 version 16.0.0 2019-05-02 06:31:13 -07:00
ecf61ecdef [apis] regnerate 2019-05-02 06:30:35 -07:00
c6b9c2c95f [apis] trim supported branch list 2019-05-02 06:29:37 -07:00
acaab8358d version 15.5.0
(cherry picked from commit 9f4cf142aad61241fdf73a599c93daa9aca4a3cc)
2019-05-02 06:27:29 -07:00
7b1f726beb Update branches to include 6.8 and 7.1 (#2)
Signed-off-by: Tyler Smalley <tyler.smalley@elastic.co>
2019-05-01 16:32:18 -07:00
166 changed files with 28001 additions and 77437 deletions

17
.editorconfig Normal file
View File

@ -0,0 +1,17 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[package.json]
insert_final_newline = false
[*.{md,asciidoc}]
trim_trailing_whitespace = false
insert_final_newline = false

View File

@ -3,3 +3,6 @@ src/bower_es_js
src/lib/apis
docs
bower_components
!.eslintrc.js
dist
node_modules

View File

@ -1,41 +0,0 @@
---
extends: "@spalger/personal/es6"
env:
node: true
rules:
comma-dangle: off
semi: off
func-names: off
no-var: off
vars-on-top: off
new-cap: off
global-require: off
no-param-reassign: off
padded-blocks: off
brace-style: off
consistent-return: off
default-case: off
dot-notation: off
eqeqeq: warn
max-len: off
no-cond-assign: off
no-console: off
no-else-return: off
no-empty: off
no-restricted-syntax: warn
no-shadow: warn
no-undef: warn
no-underscore-dangle: off
no-unused-expressions: error
no-unused-vars: error
no-use-before-define: off
object-shorthand: off
one-var: off
one-var-declaration-per-line: off
prefer-arrow-callback: off
prefer-rest-params: off
prefer-template: off
quote-props: off
yoda: off

13
.eslintrc.js Normal file
View File

@ -0,0 +1,13 @@
module.exports = {
extends: ['standard', 'eslint-config-prettier'],
plugins: ['eslint-plugin-prettier'],
rules: {
'prettier/prettier': 'error',
// disable standard style-based rules, that's prettiers job
'standard/computed-property-even-spacing': 'off',
'node/no-deprecated-api': 'off',
'standard/no-callback-literal': 'off',
'handle-callback-err': 'off',
},
};

3
.gitignore vendored
View File

@ -3,15 +3,12 @@ dist
npm-debug.log
node_modules
scripts/scratch*
test/integration/yaml_suite/log
.aws-config.json
.idea
esvm
.es-snapshot-repos
## generated files
test/integration/yaml_suite/yaml_tests*.json
test/integration/yaml_suite/index*.js
src/_elasticsearch*
src/bower*/
junit-*.xml

View File

@ -3,14 +3,11 @@ bower_components
npm-debug.log
node_modules
scripts/scratch*
test/integration/yaml_suite/log
.aws-config.json
.idea
esvm
## generated files
test/integration/yaml_suite/yaml_tests*.json
test/integration/yaml_suite/index*.js
src/_elasticsearch*/
src/bower*/
junit-*.xml

6
.prettierrc Normal file
View File

@ -0,0 +1,6 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true
}

View File

@ -1 +1 @@
The changelog has moved to https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/changelog.html
The changelog has moved to https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/changelog.html

View File

@ -12,45 +12,18 @@ Please write test cases to exercise your changes.
### 3. When you are ready, run the test suite
1. Install dev dependencies.
1. Install dependencies.
```sh
npm install
yarn
```
2. Install Grunt.
2. Run the unit tests.
```sh
npm install -g grunt-cli
yarn grunt test
```
3. Run the tests. Testing the code will lint the project, run the unit tests, install local versions of elasticsearch, and run the integration tests using those installations.
```sh
grunt test
```
Or to skip the integration tests:
```sh
grunt unit_test
```
4. Optionally, run the browser tests. While this step is automated and simple, it can take several minutes for the tests to complete. Unless you are making changes to browser specific portions of the code you can probably let Travis run the browser tests for you.
Quick Option: Run them locally in your browser
```sh
grunt browser_clients:build
node ./test/utils/server
# open http://127.0.0.1:8000/unit.html
# open http://127.0.0.1:8000/builds.html
```
Run them on Sauce Labs across several browsers, operating systems, and browser versions
```sh
grunt browser_clients:test
```
### 4. Submit a pull request
Push your local changes a forked copy of the repository and submit a pull request. In the pull request, describe what your changes do and be sure to link to any conversations regarding this implementation, eg "Closes #123".

View File

@ -1,21 +1,37 @@
module.exports = function (grunt) {
const { resolve } = require('path');
module.exports = function(grunt) {
// load plugins
require('load-grunt-config')(grunt, {
configPath: __dirname + '/grunt/config',
init: true,
config: {
distDir: __dirname + '/dist',
bowerSubmodule: __dirname + '/src/bower_es_js',
meta: {
banner: '/*! <%= package.name %> - v<%= package.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= package.homepage ? " * " + package.homepage + "\\n" : "" %>' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= package.author.company %>;' +
' Licensed <%= package.license %> */\n'
}
}
grunt.config.init({
package: require('./package.json'),
distDir: resolve(__dirname, 'dist'),
bowerSubmodule: resolve(__dirname, 'src/bower_es_js'),
meta: {
banner:
'/*! <%= package.name %> - v<%= package.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= package.homepage ? " * " + package.homepage + "\\n" : "" %>' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= package.author.company %>;' +
' Licensed <%= package.license %> */\n',
},
clean: require('./grunt/config/clean'),
compress: require('./grunt/config/compress'),
concat: require('./grunt/config/concat'),
copy: require('./grunt/config/copy'),
run: require('./grunt/config/run'),
uglify: require('./grunt/config/uglify'),
webpack: require('./grunt/config/webpack'),
});
// load task definitions
grunt.loadTasks('grunt');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-run');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-webpack');
require('./grunt/browser_clients')(grunt);
require('./grunt/tasks')(grunt);
};

View File

@ -1,4 +1,12 @@
# elasticsearch.js 15.4.1
# elasticsearch.js 16.5.0
---
#### We have released the [new JavaScript client](https://www.elastic.co/blog/new-elasticsearch-javascript-client-released)!
*In the next months this client will be deprecated, so you should start migrating your codebase as soon as possible.<br/>
We have built a [migration guide](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/breaking-changes.html) that will help you move to the new client quickly, and if you have questions or need help, please [open an issue](https://github.com/elastic/elasticsearch-js/issues/new/choose).*
---
The official low-level Elasticsearch client for Node.js and the browser.
@ -8,7 +16,7 @@ The official low-level Elasticsearch client for Node.js and the browser.
## Features
- One-to-one mapping with REST API and the other official clients
- Generalized, pluggable architecture. See [Extending Core Components](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/extending_core_components.html)
- Generalized, pluggable architecture. See [Extending Core Components](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/extending_core_components.html)
- Configurable, automatic discovery of cluster nodes
- Persistent, Keep-Alive connections
- Load balancing (with pluggable selection strategy) across all available nodes.
@ -23,16 +31,16 @@ npm install elasticsearch
## Use in the Browser
Check out the [Browser Builds](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/browser-builds.html) doc page for help downloading and setting up the client for use in the browser.
Check out the [Browser Builds](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/browser-builds.html) doc page for help downloading and setting up the client for use in the browser.
## Docs
- [Quick Start](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/quick-start.html)
- [Browser Builds](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/browser-builds.html)
- [API](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html)
- [Configuration](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html)
- [Development/Contributing](https://github.com/elastic/elasticsearch-js/blob/master/CONTRIBUTING.md)
- [Extending Core Components](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/extending_core_components.html)
- [Logging](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/logging.html)
- [Quick Start](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/quick-start.html)
- [Browser Builds](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/browser-builds.html)
- [API](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/api-reference.html)
- [Configuration](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/configuration.html)
- [Development/Contributing](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/contributing.html)
- [Extending Core Components](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/extending_core_components.html)
- [Logging](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/logging.html)
## Questions?
@ -41,7 +49,7 @@ You can probably find help in [#kibana](https://kiwiirc.com/client/irc.freenode.
## Supported Elasticsearch Versions
Elasticsearch.js provides support for, and is regularly tested against, Elasticsearch releases 0.90.12 and greater. We also test against the latest changes in several branches in the Elasticsearch repository. To tell the client which version of Elastisearch you are using, and therefore the API it should provide, set the `apiVersion` config param. [More info](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html#config-options)
Elasticsearch.js provides support for, and is regularly tested against, Elasticsearch releases 0.90.12 and greater. We also test against the latest changes in several branches in the Elasticsearch repository. To tell the client which version of Elasticsearch you are using, and therefore the API it should provide, set the `apiVersion` config param. [More info](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/configuration.html#config-options)
## Examples
@ -50,7 +58,8 @@ Create a client instance
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
log: 'trace',
apiVersion: '7.2', // use the same version of your Elasticsearch instance
});
```
@ -99,7 +108,7 @@ for (const tweet of response.hits.hits) {
}
```
More examples and detailed information about each method are available [here](http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html)
More examples and detailed information about each method are available [here](https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/index.html)
## License

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -4,20 +4,20 @@
The <<api-reference>> describes the type that each parameter accepts, this reference describes each of those types in more a little more detail.
[horizontal]
`Boolean`[[api-param-type-boolean]]:: -- `true` or `false`.
[[api-param-type-boolean]]`Boolean`:: -- `true` or `false`.
`Number`[[api-param-type-number]]:: -- A basic JavaScript number.
[[api-param-type-number]]`Number`:: -- A basic JavaScript number.
`String`[[api-param-type-string]]:: -- A basic JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String[String].
[[api-param-type-string]]`String`:: -- A basic JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String[String].
`String[]`[[api-param-type-string-array]]:: -- An array of strings.
[[api-param-type-string-array]]`String[]`:: -- An array of strings.
`Object`[[api-param-type-object]]:: -- A JSON serializable object.
[[api-param-type-object]]`Object`:: -- A JSON serializable object.
`Object[]`[[api-param-type-object-array]]:: -- An array of JSON serializable objects.
[[api-param-type-object-array]]`Object[]`:: -- An array of JSON serializable objects.
`JSON`[[api-param-type-json]]:: -- A string or `Buffer` containing a serialized JSON object.
[[api-param-type-json]]`JSON`:: -- A string or `Buffer` containing a serialized JSON object.
`JSONLines`[[api-param-type-json-lines]]:: -- A string or `Buffer` of new-line (`\n`) delimited JSON objects.
[[api-param-type-json-lines]]`JSONLines`:: -- A string or `Buffer` of new-line (`\n`) delimited JSON objects.
`DurationString`[[api-param-type-duration-string]]:: -- A string that represents a duration of time with a number followed by an https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#time-units[elasticsearch time unit]. `30m` is thirty minutes, `2d` is two days, and so on.
[[api-param-type-duration-string]]`DurationString`:: -- A string that represents a duration of time with a number followed by an https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#time-units[elasticsearch time unit]. `30m` is thirty minutes, `2d` is two days, and so on.

View File

@ -22,7 +22,7 @@ npm install elasticsearch-browser
---------
=== Download
* v15.4.1: https://download.elasticsearch.org/elasticsearch/elasticsearch-js/elasticsearch-js-15.4.1.zip[zip], https://download.elasticsearch.org/elasticsearch/elasticsearch-js/elasticsearch-js-15.4.1.tar.gz[tar.gz]
* v16.5.0: https://download.elasticsearch.org/elasticsearch/elasticsearch-js/elasticsearch-js-16.5.0.zip[zip], https://download.elasticsearch.org/elasticsearch/elasticsearch-js/elasticsearch-js-16.5.0.tar.gz[tar.gz]
=== Angular Build
* Registers an `esFactory` factory in the `"elasticsearch"` module

View File

@ -1,6 +1,33 @@
[[changelog]]
== Changelog
=== 16.5.0(Oct 31 2019)
* apiVersion `"7.4"` is now the default
=== 16.4.0(Jul 10 2019)
* apiVersion `"7.3"` is now the default
=== 16.3.0 (Jul 10 2019)
* Removed many development dependencies
* Switched to standard + prettier linting config. Testing indicates that this doesn't have any effect on the external API but it produces thousands of changes so releasing as a minor version bump just to be safe.
=== 16.2.0 (Jul 3 2019)
* apiVersion `"7.2"` is now the default
* Dropped support for old `6.7` version
=== 16.1.1 (Jun 4 2019)
* Updated readme
=== 16.1.0 (May 29 2019)
* apiVersion `"7.1"` is now the default
=== 16.0.0 (May 2 2019)
* apiVersion `"7.0"` is now the default
* Dropped support for old 6.x versions, and all versions before 5.6
=== 15.5.0 (May 1 2019)
* apiVersion `"6.7"` is now the default
=== 15.4.1 (Feb 6 2019)
* Drop support for old versions in the 5.x line, only 5.6 is maintained
@ -205,7 +232,7 @@ const client = new elasticsearch.Client({
=== 1.5 (Feb 6 2014)
* Switched out `keepaliveagent` dependency with `forever-agent`, which is used in the ever popular `request` module, and is much simpler
* The option to use keep-alive is now all or nothing. `maxKeepAliveTime` and `maxKeepAliveRequests` config parameters have been replaced by `keepAlive`, which will keeps at least `minSockets` connections open forever. See: http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html
* The option to use keep-alive is now all or nothing. `maxKeepAliveTime` and `maxKeepAliveRequests` config parameters have been replaced by `keepAlive`, which will keeps at least `minSockets` connections open forever. See: <<configuration>>
* Closing the client with `keepAlive` turned on will allow the process to exit. https://github.com/elastic/elasticsearch-js/issues/40
* Fixed a bug that caused invalid param/type errors to not be reported properly, in the browser builds that use promises
* added the cat.threadPool to the master/1.0/1.x apis

View File

@ -16,7 +16,7 @@ WARNING: Due to the complex nature of the configuration, the config object you p
[[config-options]]
=== Config options
[horizontal]
`host or hosts`[[config-hosts]]::
[[config-hosts]]`host or hosts`::
`String, String[], Object[]` -- Specify the hosts that this client will connect to. If sniffing is enabled, or you call `client.sniff()`, this list will be used as seeds to discover the rest of your cluster.
+
The value(s) are passed to the <<host-reference,`Host`>> constructor. `Host` objects can help enforce path-prefixes, default headers and query strings, and can be helpful in making more intelligent selection algorithms; Head over to <<host-reference,the `Host` docs>> for more information.
@ -29,7 +29,7 @@ Default:::
------
`httpAuth`[[config-http-auth]]:: `String` -- Specifies the default http auth as a String with username and password separated by a colon (eg. `user:pass`). Applies to any host defined in the original config, and any hosts discovered while sniffing.
[[config-http-auth]]`httpAuth`:: `String` -- Specifies the default http auth as a String with username and password separated by a colon (eg. `user:pass`). Applies to any host defined in the original config, and any hosts discovered while sniffing.
`log`[[config-log]]:: `String, String[], Object, Object[], Constructor` -- Unless a constructor is specified, this sets the output settings for the bundled logger. See the section on configuring-logging[logging] for more information.
@ -48,43 +48,37 @@ Default in Node:::
`apiVersion`[[config-api-version]]:: `String` -- Change the API that they client provides, specify the major version of the Elasticsearch nodes you will be connecting to.
[[config-api-version]]`apiVersion`:: `String` -- Change the API that they client provides, specify the major version of the Elasticsearch nodes you will be connecting to.
+
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 ::: `'6.6'`
Default ::: `'7.4'`
Options in node :::
* `'6.6'`
* `'6.5'`
* `'6.4'`
* `'6.3'`
* `'6.2'`
* `'6.1'`
* `'6.0'`
* `'7.4'`
* `'7.3'`
* `'7.2'`
* `'7.1'`
* `'7.0'`
* `'6.8'`
* `'5.6'`
* `'2.4'`
* `'1.7'`
* `'0.90'`
* `'6.7'` (unstable)
* `'7.0'` (unstable)
* `'7.5'` (unstable)
* `'7.x'` (unstable)
* `'master'` (unstable)
Options in the browser :::
* `'6.6'`
* `'6.5'`
* `'6.4'`
* `'6.3'`
* `'6.2'`
* `'6.7'` (unstable)
* `'7.0'` (unstable)
* `'7.4'`
* `'7.3'`
* `'7.2'`
* `'7.1'`
* `'7.0'`
* `'7.5'` (unstable)
* `'7.x'` (unstable)
* `'master'` (unstable)
`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`.
[[config-plugins]]`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`.
+
`Constructor` is the class that will be newed up to create the client instance. It's prototype contains the api methods that correlate to the `apiVersion` requested.
+
@ -93,7 +87,7 @@ Options in the browser :::
`components` is a map of the internal classes for this version of the elasticsearch client. The values on this object are listed https://github.com/elastic/elasticsearch-js/blob/master/src/lib/client.js#L80[here].
`sniffOnStart`[[config-sniff-on-start]]:: `Boolean` -- Should the client attempt to detect the rest of the cluster when it is first instantiated?
[[config-sniff-on-start]]`sniffOnStart`:: `Boolean` -- Should the client attempt to detect the rest of the cluster when it is first instantiated?
Default::: `false`
@ -101,7 +95,7 @@ Default::: `false`
`sniffInterval`[[config-sniff-interval]]:: `Number, false` -- Every `n` milliseconds, perform a sniff operation and make sure our list of nodes is complete.
[[config-sniff-interval]]`sniffInterval`:: `Number, false` -- Every `n` milliseconds, perform a sniff operation and make sure our list of nodes is complete.
Default::: `false`
@ -109,14 +103,14 @@ Default::: `false`
`sniffOnConnectionFault`[[config-sniff-on-connection-fault]]:: `Boolean` -- Should the client immediately sniff for a more current list of nodes when a connection dies?
[[config-sniff-on-connection-fault]]`sniffOnConnectionFault`:: `Boolean` -- Should the client immediately sniff for a more current list of nodes when a connection dies?
Default::: `false`
`maxRetries`[[config-max-retries]]:: `Integer` -- How many times should the client try to connect to other nodes before returning a <<connection-fault,ConnectionFault>> error.
[[config-max-retries]]`maxRetries`:: `Integer` -- How many times should the client try to connect to other nodes before returning a <<connection-fault,ConnectionFault>> error.
Default::: `3`
@ -124,7 +118,7 @@ Default::: `3`
`requestTimeout`[[config-request-timeout]]:: `Number` -- Milliseconds before an HTTP request will be aborted and retried. This can also be set per request.
[[config-request-timeout]]`requestTimeout`:: `Number` -- Milliseconds before an HTTP request will be aborted and retried. This can also be set per request.
Default::: `30000`
@ -132,47 +126,47 @@ Default::: `30000`
`deadTimeout`[[config-dead-timeout]]:: `Number` -- Milliseconds that a dead connection will wait before attempting to revive itself.
[[config-dead-timeout]]`deadTimeout`:: `Number` -- Milliseconds that a dead connection will wait before attempting to revive itself.
Default::: `60000`
`pingTimeout`[[config-ping-timeout]]:: `Number` -- Milliseconds that a ping request can take before timing out.
[[config-ping-timeout]]`pingTimeout`:: `Number` -- Milliseconds that a ping request can take before timing out.
Default::: `3000`
`maxSockets`[[config-keep-alive-max-sockets]]:: `Number` -- Maximum number of sockets to allow per host.
[[config-keep-alive-max-sockets]]`maxSockets`:: `Number` -- Maximum number of sockets to allow per host.
Default::: `Infinity`
`keepAlive`[[config-keep-alive]]:: `Boolean` -- Should the connections to the node be kept open forever? This behavior is recommended when you are connecting directly to Elasticsearch.
[[config-keep-alive]]`keepAlive`:: `Boolean` -- Should the connections to the node be kept open forever? This behavior is recommended when you are connecting directly to Elasticsearch.
Default::: `true`
`keepAliveInterval`[[config-keep-alive-interval]]:: `Number` -- How often, in milliseconds, should TCP KeepAlive packets be sent over sockets being kept alive. Only relevant if `keepAlive` is set to `true`.
[[config-keep-alive-interval]]`keepAliveInterval`:: `Number` -- How often, in milliseconds, should TCP KeepAlive packets be sent over sockets being kept alive. Only relevant if `keepAlive` is set to `true`.
Default::: `1000`
`keepAliveMaxFreeSockets`[[config-keep-alive-max-free-sockets]]:: `Number` -- Maximum number of inactive sockets to keep connected to a node. Only relevant if `keepAlive` is set to `true`.
[[config-keep-alive-max-free-sockets]]`keepAliveMaxFreeSockets`:: `Number` -- Maximum number of inactive sockets to keep connected to a node. Only relevant if `keepAlive` is set to `true`.
Default::: `256`
`keepAliveFreeSocketTimeout`[[config-keep-alive-free-socket-timeout]]:: `Number` -- Sets inactive sockets to timeout after milliseconds of inactivity. Only relevant if `keepAlive` is set to `true`.
[[config-keep-alive-free-socket-timeout]]`keepAliveFreeSocketTimeout`:: `Number` -- Sets inactive sockets to timeout after milliseconds of inactivity. Only relevant if `keepAlive` is set to `true`.
Default::: `60000`
`suggestCompression`[[config-suggest-compression]]:: `Boolean` -- The client should inform Elasticsearch, on each request, that it can accept compressed responses. In order for the responses to actually be compressed, you must enable `http.compression` in Elasticsearch. See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-http.html[these docs] for additional info.
[[config-suggest-compression]]`suggestCompression`:: `Boolean` -- The client should inform Elasticsearch, on each request, that it can accept compressed responses. In order for the responses to actually be compressed, you must enable `http.compression` in Elasticsearch. See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-http.html[these docs] for additional info.
Default::: `false`
`connectionClass`[[config-connection-class]]:: `String, Constructor` -- Defines the class that will be used to create connections to store in the connection pool. If you are looking to implement additional protocols you should probably start by writing a Connection class that extends the ConnectionAbstract.
[[config-connection-class]]`connectionClass`:: `String, Constructor` -- Defines the class that will be used to create connections to store in the connection pool. If you are looking to implement additional protocols you should probably start by writing a Connection class that extends the ConnectionAbstract.
Defaults:::
* Node: `"http"`
@ -181,12 +175,12 @@ Defaults:::
* jQuery Build: `"jquery"`
`sniffedNodesProtocol`[[config-sniffed-nodes-protocol]]:: `String` -- Defines the protocol that will be used to communicate with nodes discovered during sniffing.
[[config-sniffed-nodes-protocol]]`sniffedNodesProtocol`:: `String` -- Defines the protocol that will be used to communicate with nodes discovered during sniffing.
Default::: If all of the hosts/host passed to the client via configuration use the same protocol then this defaults to that protocol, otherwise it defaults to `"http"`.
`ssl`[[config-ssl]]:: `Object` -- An object defining HTTPS/SSL configuration to use for all nodes. The properties of this mimic the options accepted by http://nodejs.org/docs/latest/api/tls.html#tls_tls_connect_port_host_options_callback[`tls.connect()`] with the exception of `rejectUnauthorized`, which defaults to `false` allowing self-signed certificates to work out-of-the-box.
[[config-ssl]]`ssl`:: `Object` -- An object defining HTTPS/SSL configuration to use for all nodes. The properties of this mimic the options accepted by http://nodejs.org/docs/latest/api/tls.html#tls_tls_connect_port_host_options_callback[`tls.connect()`] with the exception of `rejectUnauthorized`, which defaults to `false` allowing self-signed certificates to work out-of-the-box.
+
Additional information available in <<auth-reference>>.
@ -216,7 +210,7 @@ var client = new elasticsearch.Client({
-----
`selector`[[config-selector]]:: `String, Function` -- This function will be used to select a connection from the ConnectionPool. It should received a single argument, the list of "active" connections, and return the connection to use. Use this selector to implement special logic for your client such as preferring nodes in a certain rack or data-center.
[[config-selector]]`selector`:: `String, Function` -- This function will be used to select a connection from the ConnectionPool. It should received a single argument, the list of "active" connections, and return the connection to use. Use this selector to implement special logic for your client such as preferring nodes in a certain rack or data-center.
+
To make this function asynchronous, accept a second argument which will be the callback to use. The callback should be called Node-style with a possible error like: `cb(err, selectedConnection)`.
@ -230,7 +224,7 @@ Options:::
`defer`[[config-defer]]:: `Function` -- Override the way that the client creates promises. If you would rather use any other promise library this is how you'd do that. Elasticsearch.js expects that the defer object has a `promise` property (which will be returned to promise consumers), as well as `resolve` and `reject` methods.
[[config-defer]]`defer`:: `Function` -- Override the way that the client creates promises. If you would rather use any other promise library this is how you'd do that. Elasticsearch.js expects that the defer object has a `promise` property (which will be returned to promise consumers), as well as `resolve` and `reject` methods.
Default::: Defer object created with ES6 Promise
@ -248,7 +242,7 @@ var client = new elasticsearch.Client({
`nodesToHostCallback`[[config-nodes-to-host-callback]]:: `Function` - This function will receive the list of nodes returned from the `_cluster/nodes` API during a sniff operation. The function should return an array of objects which match the <<config-hosts,specification for the `hosts` config>>.
[[config-nodes-to-host-callback]]`nodesToHostCallback`:: `Function` - This function will receive the list of nodes returned from the `_cluster/nodes` API during a sniff operation. The function should return an array of objects which match the <<config-hosts,specification for the `hosts` config>>.
Default:::
see https://github.com/elasticsearch/elasticsearch-js/blob/master/src/lib/nodes_to_host.js[nodes_to_host.js]
@ -256,7 +250,7 @@ see https://github.com/elasticsearch/elasticsearch-js/blob/master/src/lib/nodes_
`createNodeAgent`[[config-create-node-agent]]:: `Function` -- Override the way that the client creates node.js `Agent`[https://nodejs.org/api/http.html#http_class_http_agent] objects. The value of this property will be executed every time a new Node is added to the client (either from the initial seed or from sniffing) and can return any value that node's http(s) module accepts as `agent:` configuration.
[[config-create-node-agent]]`createNodeAgent`:: `Function` -- Override the way that the client creates node.js `Agent`[https://nodejs.org/api/http.html#http_class_http_agent] objects. The value of this property will be executed every time a new Node is added to the client (either from the initial seed or from sniffing) and can return any value that node's http(s) module accepts as `agent:` configuration.
+
The function is called with two arguments, first an `HttpConnector`[http://github.com/spalger/elasticsearch-js/blob/master/src/lib/connectors/http.js] object and the second the config object initially passed when creating the client.

View File

@ -22,26 +22,18 @@ include::development.asciidoc[]
include::api_methods.asciidoc[]
include::api_methods_6_5.asciidoc[]
include::api_methods_7_3.asciidoc[]
include::api_methods_6_4.asciidoc[]
include::api_methods_7_2.asciidoc[]
include::api_methods_6_3.asciidoc[]
include::api_methods_7_1.asciidoc[]
include::api_methods_6_2.asciidoc[]
include::api_methods_7_0.asciidoc[]
include::api_methods_6_1.asciidoc[]
include::api_methods_6_0.asciidoc[]
include::api_methods_6_8.asciidoc[]
include::api_methods_5_6.asciidoc[]
include::api_methods_2_4.asciidoc[]
include::api_methods_1_7.asciidoc[]
include::api_methods_0_90.asciidoc[]
include::changelog.asciidoc[]
include::host.asciidoc[]

View File

@ -1,16 +1,12 @@
module.exports = function (grunt) {
const Fs = require('fs');
const { resolve } = require('path');
const readline = require('readline');
grunt.registerTask('browser_clients:dev', [
'run:browser_test_server:keepalive'
]);
const chalk = require('chalk');
const AWS = require('aws-sdk');
grunt.registerTask('browser_clients:test', [
'browser_clients:build',
'run:browser_test_server',
'saucelabs-mocha:all'
]);
grunt.registerTask('browser_clients:build', function () {
module.exports = function(grunt) {
grunt.registerTask('browser_clients:build', function() {
// prevent this from running more than once accidentally
grunt.task.renameTask('browser_clients:build', 'browser_clients:rebuild');
grunt.task.registerTask('browser_clients:build', []);
@ -28,18 +24,17 @@ module.exports = function (grunt) {
grunt.registerTask('browser_clients:distribute', [
'browser_clients:build',
'_upload_archive:master'
'_upload_archive:master',
]);
grunt.registerTask('browser_clients:release', [
'prompt:confirm_release',
'_check_for_confirmation',
'prompt_confirm_release',
'browser_clients:build',
'_upload_archive:release',
'run:clone_bower_repo',
'run:checkout_bower_repo_master',
'copy:dist_to_bower',
'run:release_bower_tag'
'run:release_bower_tag',
]);
grunt.registerTask('browser_clients:push_prerelease', [
@ -47,25 +42,78 @@ module.exports = function (grunt) {
'run:clone_bower_repo',
'run:checkout_bower_repo_prerelease',
'copy:dist_to_bower',
'run:push_prerelease_branch'
'run:push_prerelease_branch',
]);
grunt.registerTask('_upload_archive', function (type) {
grunt.registerTask('_upload_archive', function(type) {
this.requires(['browser_clients:build']);
grunt.task.run([
'copy:dist_to_named_dir',
'compress:' + type + '_zip',
'compress:' + type + '_tarball',
'aws_s3:upload_archives'
'upload_to_s3',
]);
});
grunt.registerTask('_check_for_confirmation', function () {
if (grunt.config.get('confirm.release')) {
grunt.log.verbose.writeln('release confirmed');
} else {
throw new Error('Aborting release');
}
grunt.registerTask('prompt_confirm_release', function() {
const done = this.async();
const version = grunt.config.get('package.version');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(
`Are you sure you want to ${chalk.bold(
'overwrite/release'
)} version ${chalk.bold(version)} of elasticsearch-js [Yn]: `,
resp => {
const answer = resp.trim().toLowerCase();
const confirm = answer === '' || answer === 'y' || answer === 'yes';
if (!confirm) {
grunt.fatal(new Error('Aborting release'));
}
rl.close();
done();
}
);
});
grunt.registerTask('upload_to_s3', function() {
const done = this.async();
Promise.resolve()
.then(async () => {
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET,
});
const archivesDir = resolve(grunt.config.get('distDir'), 'archives');
const bucket = 'download.elasticsearch.org';
for (const name of Fs.readdirSync(archivesDir)) {
grunt.log.writeln(`Uploading ${name} to ${bucket}`);
await s3
.putObject({
ACL: 'public-read',
Body: Fs.createReadStream(resolve(archivesDir, name)),
Bucket: bucket,
Key: `elasticsearch/elasticsearch-js/${name}`,
ContentDisposition: 'attachment',
})
.promise();
grunt.log.ok(`${name} complete`);
}
done();
})
.catch(error => {
grunt.fatal(error);
});
});
};

View File

@ -1,21 +0,0 @@
module.exports = {
upload_archives: {
files: [
{
expand: true,
cwd: '<%= distDir %>/archives',
src: '*',
dest: 'elasticsearch/elasticsearch-js/'
},
],
options: {
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET,
bucket: 'download.elasticsearch.org',
access: 'public-read',
params: {
'ContentDisposition': 'attachment'
}
}
}
};

View File

@ -1,5 +1,5 @@
module.exports = {
dist: {
src: ['<%= distDir %>']
}
src: ['<%= distDir %>'],
},
};

View File

@ -5,8 +5,8 @@ function archive(out) {
src: 'elasticsearch-js/*',
expand: true,
options: {
archive: '<%= distDir %>/archives/' + out
}
archive: '<%= distDir %>/archives/' + out,
},
};
}
@ -14,5 +14,5 @@ module.exports = {
master_zip: archive('elasticsearch-js-master.zip'),
master_tarball: archive('elasticsearch-js-master.tar.gz'),
release_zip: archive('elasticsearch-js-<%= package.version %>.zip'),
release_tarball: archive('elasticsearch-js-<%= package.version %>.tar.gz')
release_tarball: archive('elasticsearch-js-<%= package.version %>.tar.gz'),
};

View File

@ -1,18 +1,24 @@
module.exports = {
dist_banners: {
files: {
'<%= distDir %>/elasticsearch.angular.js': '<%= distDir %>/elasticsearch.angular.js',
'<%= distDir %>/elasticsearch.angular.min.js': '<%= distDir %>/elasticsearch.angular.min.js',
'<%= distDir %>/elasticsearch.jquery.js': '<%= distDir %>/elasticsearch.jquery.js',
'<%= distDir %>/elasticsearch.jquery.min.js': '<%= distDir %>/elasticsearch.jquery.min.js',
'<%= distDir %>/elasticsearch.angular.js':
'<%= distDir %>/elasticsearch.angular.js',
'<%= distDir %>/elasticsearch.angular.min.js':
'<%= distDir %>/elasticsearch.angular.min.js',
'<%= distDir %>/elasticsearch.jquery.js':
'<%= distDir %>/elasticsearch.jquery.js',
'<%= distDir %>/elasticsearch.jquery.min.js':
'<%= distDir %>/elasticsearch.jquery.min.js',
'<%= distDir %>/elasticsearch.js': '<%= distDir %>/elasticsearch.js',
'<%= distDir %>/elasticsearch.min.js': '<%= distDir %>/elasticsearch.min.js'
'<%= distDir %>/elasticsearch.min.js':
'<%= distDir %>/elasticsearch.min.js',
},
options: {
banner: '<%= meta.banner %>\n' +
';(function () {\n' +
'/* prevent lodash from detecting external amd loaders */var define; \n',
footer: '\n}());'
}
}
banner:
'<%= meta.banner %>\n' +
';(function () {\n' +
'/* prevent lodash from detecting external amd loaders */var define; \n',
footer: '\n}());',
},
},
};

View File

@ -3,12 +3,12 @@ module.exports = {
cwd: '<%= distDir %>',
src: '*.js',
dest: '<%= distDir %>/elasticsearch-js/',
expand: true
expand: true,
},
dist_to_bower: {
cwd: '<%= distDir %>',
src: '*.js',
dest: '<%= bowerSubmodule %>',
expand: true
}
expand: true,
},
};

View File

@ -1,116 +0,0 @@
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 Version = require('../../scripts/Version');
var versionedOpts = [
{
version: '*',
directory: fromRoot('esvm'),
nodes: 1,
quiet: false,
logLevel: 'ERROR',
config: {
'path.data': fromRoot('esvm/data_dir'),
'node.name': 'elasticsearch_js_test_runner',
'cluster.name': 'elasticsearch_js_test_runners',
'http.port': port,
'network.host': host,
'discovery.zen.minimum_master_nodes': 1
}
},
{
version: '<3',
config: {
'discovery.zen.ping.multicast.enabled': false
}
},
{
version: '<1.6',
config: {
'discovery.zen.ping_timeout': 1
}
},
{
version: '^1.2 <1.6',
config: {
'node.bench': true,
'script.disable_dynamic': false
}
},
{
version: '>=1.6 <5.0',
config: {
'node.bench': true
}
},
{
version: '>2.0 <5.0',
config: {
'node.testattr': 'test'
}
},
{
version: '>=5.0',
config: {
'node.attr.testattr': 'test'
}
},
{
version: '>=1.6 <5.0',
config: {
'script.indexed': true
}
},
{
version: '>=1.6',
config: {
'script.inline': true,
'path.repo': process.env.ES_PATH_REPO || fromRoot('.es-snapshot-repos'),
'repositories.url.allowed_urls': 'http://snapshot.*'
}
}
];
// targets for each branch
gruntUtils.branches.forEach(function (branch) {
exports[branch] = {
options: Version.fromBranch(branch).mergeOpts(versionedOpts, {
branch: branch,
fresh: true
})
};
});
// ci target, based on env variables
(function () {
var v;
var opts = {
config: {
'http.port': port
}
};
if (release) {
v = new Version(String(release).replace(/^v/, ''));
opts.version = v.version;
}
else if (ref) {
v = new Version.fromBranch(String(ref).replace(/v?(\d+\.\d+)\..+/, '$1'));
opts.branch = ref;
opts.fresh = true;
}
else {
return;
}
exports.ci_env = {
options: v.mergeOpts(versionedOpts, opts)
};
}());

View File

@ -1,81 +0,0 @@
var root = require('find-root')(__dirname);
var rel = require('path').resolve.bind(null, root);
var rootReq = function (p) { return require(rel(p)); };
var utils = rootReq('src/lib/utils');
var grunt = require('grunt');
var JENKINS_REPORTER = rel('test/utils/jenkins-reporter.js');
var config = {
unit: {
src: 'test/unit/index.js',
options: {
reporter: 'nyan'
}
},
ci_unit: {
src: 'test/unit/index.js',
options: {
reporter: 'spec'
}
},
jenkins_unit: {
src: 'test/unit/index.js',
options: {
reporter: JENKINS_REPORTER
}
},
// run the unit tests, and update coverage.html
make_coverage_html: {
src: 'test/unit/coverage.js',
options: {
reporter: 'html-cov',
instrument: false
}
},
// for use by travis
ship_coverage: {
src: 'test/unit/coverage.js',
options: {
reporter: 'mocha-lcov-reporter',
coveralls: true,
instrument: false
}
},
integration: {
src: null,
options: {
reporter: 'spec'
}
},
jenkins_integration: {
src: null,
options: {
reporter: JENKINS_REPORTER
}
}
};
grunt.registerTask('mocha_integration', function (branch) {
grunt.config.set(
'mochacov.integration.src',
'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js'
);
grunt.task.run('mochacov:integration');
});
grunt.registerTask('mocha_jenkins_integration', function (branch) {
grunt.config.set(
'mochacov.jenkins_integration.src',
'test/integration/yaml_suite/index_' + utils.snakeCase(branch) + '.js'
);
grunt.task.run('mochacov:jenkins_integration');
});
module.exports = config;

View File

@ -1,6 +0,0 @@
module.exports = {
coverage: {
path: 'coverage.html',
app: 'Google Chrome'
}
};

View File

@ -1,12 +0,0 @@
module.exports = {
confirm_release: {
options: {
questions: [{
config: 'confirm.release',
type: 'confirm',
message: 'Are you sure you want to overwrite/release version <%= package.version %> of elasticsearch-js',
default: false
}]
}
}
};

View File

@ -1,61 +1,60 @@
var gruntUtils = require('../utils');
const { REPO_ROOT, branches } = require('../utils');
var config = {
module.exports = {
generate: {
exec: 'node ./scripts/generate/index.js',
options: {
passArgs: [
'verbose'
]
}
},
browser_test_server: {
exec: 'node ./test/utils/server',
options: {
wait: false,
quiet: false,
ready: /listening/
}
passArgs: ['verbose'],
},
},
clone_bower_repo: {
exec: [
'test -d src/bower_es_js',
'git clone git@github.com:elastic/bower-elasticsearch-js.git <%= bowerSubmodule %>'
'git clone git@github.com:elastic/bower-elasticsearch-js.git <%= bowerSubmodule %>',
].join(' || '),
options: {
quiet: true
}
quiet: true,
},
},
checkout_bower_repo_master: {
exec: 'git checkout master',
options: {
cwd: '<%= bowerSubmodule %>',
quiet: true
}
quiet: true,
},
},
checkout_bower_repo_prerelease: {
exec: 'git checkout prerelease',
options: {
cwd: '<%= bowerSubmodule %>',
quiet: true
}
quiet: true,
},
},
push_prerelease_branch: {
exec: 'git add -A && git commit -m "prerelease build" && git push origin prerelease',
exec:
'git add -A && git commit -m "prerelease build" && git push origin prerelease',
options: {
cwd: '<%= bowerSubmodule %>',
quite: true
}
quite: true,
},
},
release_bower_tag: {
exec: 'node ./scripts/release/bower'
}
exec: 'node ./scripts/release/bower',
},
mocha: {
cmd: process.execPath,
args: ['scripts/mocha'],
cwd: REPO_ROOT,
},
};
gruntUtils.branches.forEach(function (branch) {
config['generate_' + branch] = {
exec: 'node ./scripts/generate/index.js --branch=' + branch
branches.forEach(function(branch) {
module.exports['generate_' + branch] = {
exec: 'node ./scripts/generate/index.js --branch=' + branch,
};
});
module.exports = config;

View File

@ -1,36 +0,0 @@
var slk = require('../../test/utils/slk');
module.exports = {
all: {
options: {
urls: [
'http://127.0.0.1:8000/unit.html',
'http://127.0.0.1:8000/builds.html'
],
testname: 'es.js client tests',
build: process.env.TRAVIS_BUILD_ID,
concurrency: 10,
username: slk.user,
key: slk.key,
browsers: [
{
browserName: 'googlechrome',
platform: 'XP'
},
{
browserName: 'firefox',
platform: 'Linux'
},
{
browserName: 'internet explorer',
version: '11',
platform: 'Windows 8.1'
},
{
browserName: 'internet explorer',
version: '10',
platform: 'Windows 8'
}
]
}
}
};

View File

@ -2,12 +2,14 @@ module.exports = {
dist: {
files: {
'<%= distDir %>/elasticsearch.min.js': '<%= distDir %>/elasticsearch.js',
'<%= distDir %>/elasticsearch.angular.min.js': '<%= distDir %>/elasticsearch.angular.js',
'<%= distDir %>/elasticsearch.jquery.min.js': '<%= distDir %>/elasticsearch.jquery.js'
'<%= distDir %>/elasticsearch.angular.min.js':
'<%= distDir %>/elasticsearch.angular.js',
'<%= distDir %>/elasticsearch.jquery.min.js':
'<%= distDir %>/elasticsearch.jquery.js',
},
options: {
preserveComments: false,
screwIE8: true
}
}
screwIE8: true,
},
},
};

View File

@ -1,16 +0,0 @@
module.exports = {
source: {
files: [
'src/**/*.js',
'grunt/**/*.js',
'test/unit/**/*.js',
'Gruntfile.js'
],
tasks: [
'mochacov:unit'
],
options: {
interrupt: true
}
}
};

View File

@ -3,5 +3,5 @@ module.exports = {
require('../../webpack_config/browser'),
require('../../webpack_config/angular'),
require('../../webpack_config/jquery'),
]
}
],
};

View File

@ -1,43 +1,12 @@
module.exports = function (grunt) {
module.exports = function(grunt) {
var Promise = require('bluebird');
var gruntUtils = require('./utils');
var readFile = Promise.promisify(require('fs').readFile);
var writeFile = Promise.promisify(require('fs').writeFile);
grunt.registerTask('test', ['run:mocha']);
// Default task runs the build process.
grunt.registerTask('default', [
'test'
]);
grunt.registerTask('test', function (branch) {
var tasks = [
branch ? 'run:generate_' + branch : 'run:generate',
'mochacov:unit'
];
var branches = branch ? [branch] : gruntUtils.branches;
process.env.ES_PORT = process.env.ES_PORT || 9400;
process.env.ES_HOST = process.env.ES_HOST || 'localhost';
branches.forEach(function (branch) {
tasks.push(
'esvm:' + branch,
'mocha_integration:' + branch,
'esvm_shutdown:' + branch
);
});
grunt.task.run(tasks);
});
grunt.registerTask('unit_test', 'mochacov:unit');
grunt.registerTask('coverage', [
'mochacov:make_coverage_html',
'open:coverage'
]);
grunt.registerTask('version', function (nextVersion) {
grunt.registerTask('version', function(nextVersion) {
var root = require('path').join.bind(null, __dirname, '..');
var readmePath = root('README.md');
var packagePath = root('package.json');
@ -46,35 +15,39 @@ module.exports = function (grunt) {
Promise.all([
require(packagePath),
readFile(readmePath, 'utf8'),
readFile(browserBuildsPath, 'utf8')
readFile(browserBuildsPath, 'utf8'),
])
.spread(function (pkg, readme, browserBuilds) {
var current = pkg.version;
.spread(function(pkg, readme, browserBuilds) {
var current = pkg.version;
pkg.version = nextVersion;
browserBuilds = gruntUtils.replaceAll(browserBuilds, current, nextVersion);
pkg.version = nextVersion;
browserBuilds = gruntUtils.replaceAll(
browserBuilds,
current,
nextVersion
);
readme = gruntUtils.replaceAll(readme, current, nextVersion);
readme = gruntUtils.replaceAll(readme, current, nextVersion);
readme = gruntUtils.replaceAll(
readme,
'/' + gruntUtils.minorVersion(current) + '.svg',
'/' + gruntUtils.minorVersion(nextVersion) + '.svg'
);
readme = gruntUtils.replaceAll(
readme,
'/' + gruntUtils.minorVersion(current) + '.svg',
'/' + gruntUtils.minorVersion(nextVersion) + '.svg'
);
readme = gruntUtils.replaceAll(
readme,
'branch=' + gruntUtils.minorVersion(current),
'branch=' + gruntUtils.minorVersion(nextVersion)
);
readme = gruntUtils.replaceAll(
readme,
'branch=' + gruntUtils.minorVersion(current),
'branch=' + gruntUtils.minorVersion(nextVersion)
);
// write all files to disk
return Promise.all([
writeFile(readmePath, readme),
writeFile(browserBuildsPath, browserBuilds),
writeFile(packagePath, JSON.stringify(pkg, null, ' '))
]);
})
.nodeify(this.async());
// write all files to disk
return Promise.all([
writeFile(readmePath, readme),
writeFile(browserBuildsPath, browserBuilds),
writeFile(packagePath, JSON.stringify(pkg, null, ' ')),
]);
})
.nodeify(this.async());
});
};

View File

@ -7,13 +7,17 @@ var unstable = pkg.config.unstable_es_branches;
var branches = [].concat(stable, unstable);
var gruntUtils = {
branchSuffix: function (branch) {
return branch === gruntUtils.branches._default ? '' : '_' + utils.snakeCase(branch);
REPO_ROOT: root,
branchSuffix: function(branch) {
return branch === gruntUtils.branches._default
? ''
: '_' + utils.snakeCase(branch);
},
branches: branches,
stableBranches: stable,
unstableBranches: unstable,
browserBranches: stable.slice(0, 5).concat(unstable)
browserBranches: stable.slice(0, 5).concat(unstable),
};
gruntUtils.branches._default = pkg.config.default_api_branch;
@ -21,14 +25,17 @@ gruntUtils.branches._default = pkg.config.default_api_branch;
/*
* trim down a version id to the minor version number ('1.5.1' => '1.5')
*/
gruntUtils.minorVersion = function (version) {
return version.split('.').slice(0, 2).join('.');
gruntUtils.minorVersion = function(version) {
return version
.split('.')
.slice(0, 2)
.join('.');
};
/*
* increment the version based on the release "type"
*/
gruntUtils.increaseVersion = function (version, type) {
gruntUtils.increaseVersion = function(version, type) {
var i;
switch (type) {
case 'major':
@ -47,14 +54,14 @@ gruntUtils.increaseVersion = function (version, type) {
}
// breakout the current version
var next = version.split('.').map(function (n) {
var next = version.split('.').map(function(n) {
return parseInt(n, 10);
});
// increment the version type
next[i] += 1;
// clear out all following numbers
for (i ++; i < next.length; i++) next[i] = 0;
for (i++; i < next.length; i++) next[i] = 0;
// join back together with '.'
return next.join('.');
};
@ -62,7 +69,7 @@ gruntUtils.increaseVersion = function (version, type) {
/*
* replace all instances of `replace` with `replacement` without creating a regexp object
*/
gruntUtils.replaceAll = function (str, replace, replacement) {
gruntUtils.replaceAll = function(str, replace, replacement) {
var out = '';
var remaining = str;
var i = 0;

View File

@ -6,8 +6,8 @@
"name": "elasticsearch",
"description": "The official low-level Elasticsearch client for Node.js and the browser.",
"main": "src/elasticsearch.js",
"homepage": "http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html",
"version": "15.4.1",
"homepage": "https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/16.x/index.html",
"version": "16.5.0",
"keywords": [
"elasticsearch",
"mapping",
@ -17,7 +17,7 @@
"test": "grunt test",
"generate": "node scripts/generate",
"grunt": "grunt",
"lint": "eslint ."
"lint": "node scripts/eslint"
},
"browser": {
"./src/lib/connectors/index.js": "./src/lib/connectors/browser_index.js",
@ -29,23 +29,18 @@
"blanket": {
"pattern": "specified in test/unit/coverage.js"
},
"default_api_branch": "6.6",
"default_api_branch": "7.4",
"supported_es_branches": [
"6.6",
"6.5",
"6.4",
"6.3",
"6.2",
"6.1",
"6.0",
"5.6",
"2.4",
"1.7",
"0.90"
"7.4",
"7.3",
"7.2",
"7.1",
"7.0",
"6.8",
"5.6"
],
"unstable_es_branches": [
"6.7",
"7.0",
"7.5",
"7.x",
"master"
]
@ -53,60 +48,49 @@
"devDependencies": {
"@babel/core": "^7.0.0-beta.41",
"@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",
"babel-loader": "^8.0.0-beta",
"backport": "^3.0.2",
"blanket": "^1.2.3",
"bluebird": "^2.9.14",
"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",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-compress": "^1.2.0",
"grunt-contrib-concat": "^1.0.1",
"grunt-contrib-copy": "^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",
"sinon": "^1.17.4",
"split": "~0.3.2",
"through2": "~0.6.3",
"through2-map": "~1.4.0",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.1",
"xmlbuilder": "~0.4.3"
"webpack": "^3.10.0"
},
"license": "Apache-2.0",
"dependencies": {
@ -119,7 +103,7 @@
},
"repository": {
"type": "git",
"url": "http://github.com/elastic/elasticsearch-js.git"
"url": "https://github.com/elastic/elasticsearch-js-legacy.git"
},
"engines": {
"node": ">=0.8"

View File

@ -1,6 +1,9 @@
var _ = require('lodash');
var pkg = require('../package.json');
var branches = [...pkg.config.supported_es_branches, ...pkg.config.unstable_es_branches];
var branches = [
...pkg.config.supported_es_branches,
...pkg.config.unstable_es_branches,
];
var semver = require('semver');
function nextMajorVersion() {
@ -8,14 +11,19 @@ function nextMajorVersion() {
.map(v => parseFloat(v.split('.')[0]))
.filter(n => !isNaN(n))
.sort((a, b) => b - a)
.shift()
.shift();
return new Version(`${largestMajor + 1}.0.0`)
return new Version(`${largestMajor + 1}.0.0`);
}
function nextMinorVersion(major) {
const largestMinor = branches
.map(v => v.split('.').map(parseFloat).slice(0, 2))
.map(v =>
v
.split('.')
.map(parseFloat)
.slice(0, 2)
)
// ensure all tuples have length 2
.filter(vt => vt.length === 2)
// ensure all values in tuples are not NaN
@ -37,38 +45,37 @@ function Version(v) {
this.patch = semver.patch(v);
}
Version.fromBranch = function (branch) {
Version.fromBranch = function(branch) {
// n.m -> n.m.0
if (/^\d+\.\d+$/.test(branch)) return new Version(branch + '.0');
// n.x -> n.(maxVersion + 1).0
const match = branch.match(/^(\d+)\.x$/i)
const match = branch.match(/^(\d+)\.x$/i);
if (match) return nextMinorVersion(match[1]);
// master => (maxMajorVersion + 1).0.0
if (branch === 'master') return nextMajorVersion()
if (branch === 'master') return nextMajorVersion();
throw new Error('unable to convert branch "' + branch + '" to semver');
};
Version.prototype.increment = function (which) {
Version.prototype.increment = function(which) {
return new Version(semver.inc(this.version, which));
};
Version.prototype.satisfies = function (range) {
Version.prototype.satisfies = function(range) {
return semver.satisfies(this.version, range);
};
// merge a list of option objects, each of which has a "version" key dictating
// the range of versions those options should be included in. Options are merged
// in the order of the array
Version.prototype.mergeOpts = function (versioned, overrides) {
Version.prototype.mergeOpts = function(versioned, overrides) {
const candidates = versioned
.filter(o => this.satisfies(o.version))
.map(o => _.omit(o, 'version'))
.map(o => _.omit(o, 'version'));
return _.merge({}, overrides || {}, ...candidates)
return _.merge({}, overrides || {}, ...candidates);
};
module.exports = Version;

View File

@ -14,9 +14,12 @@ function indent(line) {
function consume(stream) {
stream
.pipe(split())
.pipe(map(indent))
.pipe(process.stdout, { end: false });
.pipe(split())
.pipe(map(indent))
.pipe(
process.stdout,
{ end: false }
);
}
function _spawn(cmd, args, opts, cb) {
@ -27,11 +30,7 @@ function _spawn(cmd, args, opts, cb) {
}
var conf = {
stdio: [
'ignore',
opts.verbose ? 'pipe' : 'ignore',
'pipe'
]
stdio: ['ignore', opts.verbose ? 'pipe' : 'ignore', 'pipe'],
};
var subdir;
@ -41,7 +40,12 @@ function _spawn(cmd, args, opts, cb) {
subdir = path.relative(root, opts.cwd);
}
console.log(chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') + cmd + ' ' + args.join(' '));
console.log(
chalk.white.bold((subdir ? subdir + ' ' : '') + '$ ') +
cmd +
' ' +
args.join(' ')
);
var cp = spawn(cmd, args, conf);
@ -58,6 +62,6 @@ function _spawn(cmd, args, opts, cb) {
return cp;
}
_spawn.exec = function (cmd, opts, cb) {
_spawn.exec = function(cmd, opts, cb) {
return _spawn('/bin/sh', ['-c', cmd], opts, cb);
};

View File

@ -1 +0,0 @@
require('backport');

View File

@ -1,328 +0,0 @@
/**
* Run the tests, and setup es if needed
*
* ENV VARS:
* RUN - a list of task names to run, specifying this turns of all other tasks
* ES_REF - the ES branch/tag we should use to generate the tests and download es
* ES_RELEASE - a specific ES release to download in use for testing
* ES_PORT - the port number we should run elasticsearch on
* ES_HOST - the hostname elasticsearch should bind to
* ES_V - a version identifier used by jenkins. don't use this
*
* Tasks:
* NODE_UNIT - run the unit tests in node (default: true)
* NODE_INTEGRATION - run the integration tests in node (default: true)
* SAUCE_LABS - run the browser tests (default: false)
* CHECK_COVERAGE - check for coverage and ship it to coveralls (default: false)
*
*******/
var Promise = require('bluebird');
var _ = require('lodash');
var through2 = require('through2');
var map = require('through2-map');
var split = require('split');
var join = require('path').join;
var cp = require('child_process');
var chalk = require('chalk');
var format = require('util').format;
var NL_RE = /(\r?\n)/g;
var ROOT = join(__dirname, '..');
var GRUNT = join(ROOT, 'node_modules', '.bin', 'grunt');
var ENV = _.clone(process.env);
var JENKINS = !!ENV.JENKINS_HOME;
var TASKS = [];
var output; // main output stream
var taskOut; // task output stream
task('NODE_UNIT', true, function () {
if (!JENKINS) {
return grunt('mochacov:ci_unit');
}
return grunt('mochacov:jenkins_unit');
});
task('NODE_INTEGRATION', true, function () {
var branch = ENV.ES_REF;
return node('scripts/generate', '--no-api', '--branch', branch)
.then(function () {
var target = (JENKINS ? 'jenkins_' : '') + 'integration:' + branch;
return grunt('esvm:ci_env', 'mocha_' + target, 'esvm_shutdown:ci_env');
});
});
task('SAUCE_LABS', false, function () {
return new Promise(function (resolve, reject) {
// build the clients and start the server, once the server is ready call trySaucelabs()
var serverTasks = ['browser_clients:build', 'run:browser_test_server:keepalive'];
spawn(GRUNT, serverTasks, function (proc) {
var toLines = split();
proc.stdout
.pipe(toLines)
.pipe(through2(function (line, enc, cb) {
cb();
if (String(line).indexOf('listening on port 8000') === -1) return;
trySaucelabs()
.finally(function () { if (proc) proc.kill(); })
.then(resolve, reject);
proc.on('exit', function () { proc = null; });
proc.stdout.unpipe(toLines);
toLines.end();
}));
})
// ignore server errors
.catch(_.noop);
// attempt to run tests on saucelabs and retry if it fails
var saucelabsAttempts = 0;
function trySaucelabs() {
saucelabsAttempts++;
return new Promise(function (resolve, reject) {
log(chalk.green('saucelabs attempt #', saucelabsAttempts));
spawn(GRUNT, ['saucelabs-mocha'], function (cp) {
var failedTests = 0;
cp.stdout
.pipe(split())
.pipe(map(function (line) {
failedTests += String(line).trim() === 'Passed: false' ? 1 : 0;
}));
cp.on('error', reject);
cp.on('exit', function (code) {
if (code > 0) {
if (failedTests > 0) {
return reject(new Error('Browser tests failed'));
}
if (saucelabsAttempts >= 3) {
return reject(new Error('Saucelabs is like really really down. Tried 3 times'));
}
log(chalk.blue('trying saucelabs again...'));
return trySaucelabs().then(resolve, reject);
}
return resolve();
});
})
// swallow spawn() errors, custom error handler in place
.catch(_.noop);
});
}
});
});
task('CHECK_COVERAGE', false, function () {
return grunt('mochacov:ship_coverage')
.catch(function () {
log('FAILED TO SHIP COVERAGE! but that\'s okay');
});
});
execTask('SETUP', function () {
return Promise.try(function readVersion() {
if (!ENV.ES_V) {
if (ENV.ES_RELEASE) {
return ['v' + ENV.ES_RELEASE, ENV.ES_RELEASE];
}
if (ENV.ES_REF) {
return [ENV.ES_REF, null];
}
}
var match;
if (match = ENV.ES_V.match(/^(.*)_nightly$/)) {
return [match[1], null];
}
if (/^(?:1\.\d+|0\.90)\..*$/.test(ENV.ES_V)) {
return ['v' + ENV.ES_V, ENV.ES_V];
}
throw new Error('unable to parse ES_V ' + ENV.ES_V);
})
.then(function readOtherConf(ver) {
if (!ver) {
throw new Error('Unable to run the ci script without at least an ES_REF or ES_RELEASE environment var.');
}
log('ES_PORT:', ENV.ES_PORT = parseInt(ENV.ES_PORT || 9400, 10));
log('ES_HOST:', ENV.ES_HOST = ENV.ES_HOST || 'localhost');
if (ver[0]) log('ES_REF:', ENV.ES_REF = ver[0]);
else delete ENV.ES_REF;
if (ver[1]) log('ES_RELEASE:', ENV.ES_RELEASE = ver[1]);
else delete ENV.ES_RELEASE;
})
.then(function readTasks() {
if (!ENV.RUN) {
return _.filter(TASKS, { default: true });
}
return ENV.RUN
.split(',')
.map(function (name) {
return _.find(TASKS, { name: name.trim() });
})
.filter(Boolean);
});
})
.then(function (queue) {
if (!queue.length) {
throw new Error('no tasks to run');
}
// Recursively do tasks until the queue is empty
return (function next() {
if (!queue.length) return;
return execTask(queue.shift()).then(next);
}());
})
.then(function () {
logImportant(chalk.bold.green('✔︎ SUCCESS'));
})
.catch(function (e) {
logImportant(chalk.bold.red('✗ FAILURE\n\n' + e.stack));
// override process exit code once it is ready to close
process.once('exit', function () {
process.exit(1);
});
});
/** ****
* utils
******/
function log() {
var chunk = format.apply(null, arguments);
(taskOut || output || process.stdout).write(chunk + '\n');
}
function logImportant(text) {
log('\n------------');
log(text);
log('------------');
}
function push(m) {
return function () {
var args = _.toArray(arguments);
var cb = args.pop();
this.push(m.apply(this, args));
cb();
};
}
function indent() {
var str = through2(
push(function (chunk) { return String(chunk).replace(NL_RE, '$1 '); }),
push(function () { return '\n'; })
);
str.push(' ');
return str;
}
function task(name, def, fn) {
if (_.isFunction(def)) {
fn = def;
def = true;
}
TASKS.push({
name: name,
default: def,
fn: fn
});
}
function execTask(name, task) {
if (_.isObject(name)) {
task = name.fn;
name = name.name;
}
output = through2();
output
.pipe(process.stdout, { end: false });
log(chalk.white.underline(name));
taskOut = through2();
taskOut
.pipe(indent())
.pipe(output);
function flushTaskOut() {
return new Promise(function (resolve) {
// wait for the taskOut to finish writing before continuing
output.once('finish', function () {
log('');
resolve();
});
taskOut.end(); // will end output as well
taskOut = output = null;
});
}
return Promise.try(task).finally(flushTaskOut);
}
function spawn(file, args, block) {
return new Promise(function (resolve, reject) {
var proc = cp.spawn(file, args, {
cwd: ROOT,
env: ENV,
stdio: [0, 'pipe', 'pipe']
});
proc.stdout.pipe(taskOut, { end: false });
proc.stderr.pipe(taskOut, { end: false });
var stdout = '';
proc.stdout
.pipe(through2(function (chunk, enc, cb) {
stdout += chunk;
cb();
}));
if (block) block(proc);
proc.on('exit', function (code) {
if (code > 0) {
reject(new Error('non-zero exit code: ' + code));
} else {
resolve(stdout);
}
});
proc.on('error', function (origErr) {
reject(new Error('Unable to execute "' + file + ' ' + args.join(' ') + '": ' + origErr.message));
});
});
}
function node(/* args... */) {
return spawn(
process.execPath,
_.toArray(arguments)
);
}
function grunt(/* args... */) {
return spawn(
GRUNT,
_.toArray(arguments)
);
}

2
scripts/eslint.js Normal file
View File

@ -0,0 +1,2 @@
process.argv.push('.');
require('eslint/bin/eslint');

View File

@ -1,25 +1,40 @@
module.exports = function (done) {
module.exports = function(done) {
var _ = require('lodash');
var gruntUtils = require('../../grunt/utils');
var chalk = require('chalk');
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
var fromRoot = _.partial(
require('path').join,
require('find-root')(__dirname)
);
var write = require('fs').writeFileSync;
var nodeApiIndex = fromRoot('src/lib/apis/index.js');
var browserApiIndex = fromRoot('src/lib/apis/browser_index.js');
write(nodeApiIndex, require('./templates').apiIndex({
branches: gruntUtils.branches
}), 'utf8');
write(
nodeApiIndex,
require('./templates').apiIndex({
branches: gruntUtils.branches,
}),
'utf8'
);
console.log(chalk.white.bold('wrote'), 'api index to', nodeApiIndex);
write(browserApiIndex, require('./templates').apiIndexBrowser({
branches: gruntUtils.browserBranches
}), 'utf8');
write(
browserApiIndex,
require('./templates').apiIndexBrowser({
branches: gruntUtils.browserBranches,
}),
'utf8'
);
console.log(chalk.white.bold('wrote'), 'browser api index to', browserApiIndex);
console.log(
chalk.white.bold('wrote'),
'browser api index to',
browserApiIndex
);
done();
};

View File

@ -1,8 +1,11 @@
module.exports = function (done) {
module.exports = function(done) {
var _ = require('lodash');
var chalk = require('chalk');
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
var fromRoot = _.partial(
require('path').join,
require('find-root')(__dirname)
);
var write = require('fs').writeFile;
var outputPath = fromRoot('docs/configuration.asciidoc');

View File

@ -1,18 +1,26 @@
module.exports = function (done) {
module.exports = function(done) {
var _ = require('lodash');
var gruntUtils = require('../../grunt/utils');
var chalk = require('chalk');
var fromRoot = _.partial(require('path').join, require('find-root')(__dirname));
var fromRoot = _.partial(
require('path').join,
require('find-root')(__dirname)
);
var write = require('fs').writeFile;
var outputPath = fromRoot('docs/index.asciidoc');
write(outputPath, require('./templates').docsIndex({
apiFiles: gruntUtils.stableBranches.map(function (branch) {
return 'api_methods' + gruntUtils.branchSuffix(branch) + '.asciidoc';
})
}), 'utf8', done);
write(
outputPath,
require('./templates').docsIndex({
apiFiles: gruntUtils.stableBranches.map(function(branch) {
return 'api_methods' + gruntUtils.branchSuffix(branch) + '.asciidoc';
}),
}),
'utf8',
done
);
console.log(chalk.white.bold('wrote'), 'doc index to', outputPath);
};

View File

@ -2,30 +2,25 @@
var async = require('async');
var fs = require('fs');
var spawn = require('../_spawn');
var argv = require('optimist')
.options({
verbose: {
alias: 'v',
default: false,
boolean: true
},
api: {
default: true,
boolean: true
},
tests: {
default: true,
boolean: true
},
update: {
default: true,
boolean: true
},
branch: {
default: null,
string: true
}
});
var argv = require('optimist').options({
verbose: {
alias: 'v',
default: false,
boolean: true,
},
api: {
default: true,
boolean: true,
},
update: {
default: true,
boolean: true,
},
branch: {
default: null,
string: true,
},
});
var path = require('path');
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
@ -59,82 +54,101 @@ var paths = {
docs: fromRoot('docs'),
docsIndex: fromRoot('docs/index.asciidoc'),
apiSrc: 'src/lib/apis',
getArchiveDir: function (branch) {
getArchiveDir: function(branch) {
return fromRoot('src/_elasticsearch_' + utils.snakeCase(branch));
},
getArchiveTarball: function (branch) {
getArchiveTarball: function(branch) {
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';
}
getSpecPathInRepo: function(branch) {
return /^v?(master|[2-9]\.)/.test(branch)
? 'rest-api-spec/src/main/resources/rest-api-spec'
: 'rest-api-spec';
},
};
function isDirectory(dir) {
var stat;
try { stat = fs.statSync(dir); } catch (e) {}
return (stat && stat.isDirectory());
try {
stat = fs.statSync(dir);
} catch (e) {}
return stat && stat.isDirectory();
}
function dirFilter(dir, fn) {
try {
return fs.readdirSync(dir)
.filter(function (name) {
return name !== '.' && name !== '..' && fn(name);
})
.map(function (filename) {
return path.join(dir, filename);
});
return fs
.readdirSync(dir)
.filter(function(name) {
return name !== '.' && name !== '..' && fn(name);
})
.map(function(filename) {
return path.join(dir, filename);
});
} catch (e) {
return [];
}
}
function dirRegex(dir, regexp) {
return dirFilter(dir, function (name) {
return dirFilter(dir, function(name) {
return name.match(regexp);
});
}
function dirOpts(dir, opts) {
opts = _.isArray(opts) ? opts : [opts];
return dirFilter(dir, function (name) {
return dirFilter(dir, function(name) {
return _.includes(opts, name);
});
}
function spawnStep(cmd, args, cwd) {
return function (done) {
spawn(cmd, args, {
verbose: argv.verbose,
cwd: cwd
}, function (status) {
done(status ? new Error('Non-zero exit code: ' + status) : void 0);
});
return function(done) {
spawn(
cmd,
args,
{
verbose: argv.verbose,
cwd: cwd,
},
function(status) {
done(status ? new Error('Non-zero exit code: ' + status) : void 0);
}
);
};
}
function initStep() {
return function (done) {
return function(done) {
if (isDirectory(paths.esSrc)) {
async.series([
spawnStep('git', ['remote', 'set-url', 'origin', esUrl], paths.esSrc)
], done);
async.series(
[spawnStep('git', ['remote', 'set-url', 'origin', esUrl], paths.esSrc)],
done
);
} else {
async.series([
spawnStep('git', ['init', '--bare', paths.esSrc], paths.root),
spawnStep('git', ['remote', 'add', 'origin', esUrl], paths.esSrc)
], done);
async.series(
[
spawnStep('git', ['init', '--bare', paths.esSrc], paths.root),
spawnStep('git', ['remote', 'add', 'origin', esUrl], paths.esSrc),
],
done
);
}
};
}
function fetchBranchesStep() {
var branchArgs = branches.map(function (b) { return b + ':' + b; });
return spawnStep('git', ['fetch', '--no-tags', '--force', 'origin'].concat(branchArgs), paths.esSrc);
var branchArgs = branches.map(function(b) {
return b + ':' + b;
});
return spawnStep(
'git',
['fetch', '--no-tags', '--force', 'origin'].concat(branchArgs),
paths.esSrc
);
}
function findGeneratedApiFiles() {
var anyApiMethodDocs = /^(configuration|index|api_methods).*\.asciidoc$/;
var anyApiJsFiled = /^.+\.js$/;
@ -143,11 +157,11 @@ function findGeneratedApiFiles() {
if (allBranches) {
return [
dirRegex(paths.docs, anyApiMethodDocs),
dirRegex(paths.apiSrc, anyApiJsFiled)
dirRegex(paths.apiSrc, anyApiJsFiled),
];
}
return branches.reduce(function (files, branch) {
return branches.reduce(function(files, branch) {
var b = utils.snakeCase(branch);
files.push(dirOpts(paths.docs, 'api_methods_' + b + '.asciidoc'));
@ -163,7 +177,6 @@ function findGeneratedApiFiles() {
}, []);
}
function clearGeneratedFiles() {
var esArchives = /^_elasticsearch_(master|[\dx_]+|\.tar)$/;
var generatedFiles = [];
@ -175,16 +188,16 @@ function clearGeneratedFiles() {
generatedFiles.push(dirRegex(paths.src, esArchives));
var rmSteps = _.chain(generatedFiles)
.flattenDeep()
.uniq()
.map(function (path) {
return spawnStep('rm', ['-rf', path]);
})
.value();
.flattenDeep()
.uniq()
.map(function(path) {
return spawnStep('rm', ['-rf', path]);
})
.value();
if (!rmSteps.length) return;
return function (done) {
return function(done) {
return async.series(rmSteps, done);
};
}
@ -198,8 +211,28 @@ function removePrevArchive(branch) {
return spawnStep('rm', ['-rf', dir], paths.root);
}
function convertToCommit(branch) {
switch (branch) {
case '5.6':
case '6.8':
case '7.0':
case '7.1':
case '7.2':
case '7.3':
return branch;
case '7.4':
return 'c31cddf27e9618582b3cd175e4e0bce320af6a14^1';
case '7.5':
return 'c31cddf27e9618582b3cd175e4e0bce320af6a14^1';
case '7.x':
return 'c31cddf27e9618582b3cd175e4e0bce320af6a14^1';
case 'master':
return '91663116221052b9aa05cc183d80c1e546073371^1';
}
}
function createArchive(branch) {
return function (done) {
return function(done) {
var dir = paths.getArchiveDir(branch);
var tarball = paths.getArchiveTarball(branch);
var specPathInRepo = paths.getSpecPathInRepo(branch);
@ -210,36 +243,62 @@ function createArchive(branch) {
return process.nextTick(done);
}
async.series([
spawnStep('mkdir', [dir], paths.root),
spawnStep('git', ['archive', '--format', 'tar', '--output', tarball, branch, specPathInRepo], paths.esSrc),
spawnStep('tar', ['-x', '-f', tarball, '-C', dir, '--strip-components', subDirCount]),
spawnStep('rm', [tarball])
], done);
async.series(
[
spawnStep('mkdir', [dir], paths.root),
spawnStep(
'git',
[
'archive',
'--format',
'tar',
'--output',
tarball,
convertToCommit(branch),
specPathInRepo,
],
paths.esSrc
),
spawnStep('tar', [
'-x',
'-f',
tarball,
'-C',
dir,
'--strip-components',
subDirCount,
]),
spawnStep('rm', [tarball]),
],
done
);
};
}
function generateStep(branch) {
return function (done) {
async.parallel([
argv.api && async.apply(require('./js_api'), branch),
argv.tests && async.apply(require('./yaml_tests'), branch)
].filter(Boolean), done);
return function(done) {
async.parallel(
[argv.api && async.apply(require('./js_api'), branch)].filter(Boolean),
done
);
};
}
var steps = [
initStep(),
clearGeneratedFiles(),
fetchBranchesStep()
].filter(Boolean);
var steps = [initStep(), clearGeneratedFiles(), fetchBranchesStep()].filter(
Boolean
);
branches.forEach(function (branch) {
steps.push(_.partial(async.series, [
removePrevArchive(branch),
createArchive(branch),
generateStep(branch)
].filter(Boolean)));
branches.forEach(function(branch) {
steps.push(
_.partial(
async.series,
[
removePrevArchive(branch),
createArchive(branch),
generateStep(branch),
].filter(Boolean)
)
);
});
if (argv.api) {
@ -251,15 +310,15 @@ if (argv.api) {
}
async.series(
steps.map(function (step) {
return function (done) {
step(function (err) {
steps.map(function(step) {
return function(done) {
step(function(err) {
console.log('----\n');
done(err);
});
};
}),
function (err) {
function(err) {
if (err) {
throw err;
}

View File

@ -1,4 +1,4 @@
module.exports = function (branch, done) {
module.exports = function(branch, done) {
/**
* Read the API actions form the rest-api-spec repo.
* @type {[type]}
@ -34,32 +34,29 @@ module.exports = function (branch, done) {
var steps = [
readSpecFiles,
function (done) {
function(done) {
parseSpecFiles(branch, done);
},
writeApiFile
writeApiFile,
];
if (!~gruntUtils.unstableBranches.indexOf(branch)) {
steps.push(
ensureDocsDir,
formatDocVars,
writeMethodDocs
);
steps.push(ensureDocsDir, formatDocVars, writeMethodDocs);
}
// generate the API
async.series(steps, function (err) {
async.series(steps, function(err) {
done(err);
});
function readSpecFiles(done) {
var apiDir = path.join(esDir, 'rest-api-spec/api/');
files = fs.readdirSync(apiDir)
.filter(function (filename) {
return filename[0] !== '_'
files = fs
.readdirSync(apiDir)
.filter(function(filename) {
return filename[0] !== '_';
})
.map(function (filename) {
.map(function(filename) {
var module = require(apiDir + filename);
delete require.cache[apiDir + filename];
return module;
@ -70,23 +67,25 @@ module.exports = function (branch, done) {
function parseSpecFiles(branch, done) {
var actions = [];
files.forEach(function (spec) {
__puke__transformSpec(branch, spec).forEach(function (action) {
files.forEach(function(spec) {
__puke__transformSpec(branch, spec).forEach(function(action) {
actions.push(action);
});
});
// collect the namespaces from the action locations
var namespaces = _.filter(_.map(actions, function (action) {
return action.location
.split('.')
.slice(0, -1)
.filter(step => step !== 'prototype')
.join('.prototype.')
}));
var namespaces = _.filter(
_.map(actions, function(action) {
return action.location
.split('.')
.slice(0, -1)
.filter(step => step !== 'prototype')
.join('.prototype.');
})
);
// seperate the proxy actions
var groups = _.groupBy(actions, function (action) {
var groups = _.groupBy(actions, function(action) {
return action.proxy ? 'proxies' : 'normal';
});
@ -94,7 +93,7 @@ module.exports = function (branch, done) {
actions: groups.normal || [],
proxies: groups.proxies || [],
namespaces: _.uniq(namespaces.sort()),
clientActionModifier: overrides.clientActionModifier
clientActionModifier: overrides.clientActionModifier,
};
if (!_.find(apiSpec.actions, { name: 'create' })) {
@ -105,7 +104,7 @@ module.exports = function (branch, done) {
name: 'create',
location: 'create',
proxy: 'index',
transformBody: 'params.op_type = \'create\';'
transformBody: "params.op_type = 'create';",
}
);
@ -116,36 +115,50 @@ module.exports = function (branch, done) {
apiSpec.proxies.push(create);
}
[].concat(apiSpec.actions, apiSpec.proxies)
.forEach(function (action) {
var examplePath = overrides.examples[action.name] || action.name + '.asciidoc';
var descriptionPath = overrides.descriptions[action.name] || action.name + '.asciidoc';
[].concat(apiSpec.actions, apiSpec.proxies).forEach(function(action) {
var examplePath =
overrides.examples[action.name] || action.name + '.asciidoc';
var descriptionPath =
overrides.descriptions[action.name] || action.name + '.asciidoc';
try {
action.examples = fs.readFileSync(fromRoot('docs/_examples', examplePath), 'utf8');
action.examples = fs.readFileSync(
fromRoot('docs/_examples', examplePath),
'utf8'
);
} catch (e) {
action.examples = '// no examples';
}
try {
action.description = fs.readFileSync(fromRoot('docs/_descriptions', descriptionPath), 'utf8');
action.description = fs.readFileSync(
fromRoot('docs/_descriptions', descriptionPath),
'utf8'
);
} catch (e) {
action.description = '// no description';
}
})
});
done();
}
function writeApiFile(done) {
var outputPath = fromRoot('src/lib/apis/' + utils.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);
console.log(
chalk.white.bold('wrote'),
apiSpec.actions.length,
'api actions to',
outputPath
);
done();
}
function ensureDocsDir(done) {
fs.stat(fromRoot('docs'), function (err, stat) {
fs.stat(fromRoot('docs'), function(err, stat) {
if (err) {
if (err.message.match(/enoent/i)) {
fs.mkdir('../../docs', done);
@ -175,36 +188,50 @@ module.exports = function (branch, done) {
done();
}
var patchBadLinks = {
'https://www.elastic.co/guide/en/elasticsearch/reference/7.4/indices-flush.html#synced-flush-api':
'https://www.elastic.co/guide/en/elasticsearch/reference/7.4/indices-synced-flush-api.html',
};
function writeMethodDocs(done) {
var filename = fromRoot('docs/api_methods' + branchSuffix + '.asciidoc');
fs.writeFile(
filename,
templates.apiMethods(docVars),
function (err) {
if (!err) {
console.log(chalk.white.bold('wrote'), branch + ' method docs to', filename);
}
done(err);
var content = templates.apiMethods(docVars);
for (const [bad, good] of Object.entries(patchBadLinks)) {
content = content.split(bad).join(good);
}
fs.writeFile(filename, content, function(err) {
if (!err) {
console.log(
chalk.white.bold('wrote'),
branch + ' method docs to',
filename
);
}
);
done(err);
});
}
function __puke__transformSpec(branch, spec) { // eslint-disable-line
var actions = [];
// itterate all of the specs within the file, should only be one
_.each(spec, function (def, name) {
_.each(spec, function(def, name) {
// camelcase the name
name = _.map(name.split('.'), utils.camelCase).join('.');
if (name === 'cat.aliases') {
def.documentation = 'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html';
def.documentation =
'http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html';
}
def.documentation = def.documentation.replace(
/^https?:\/\/.+?\/guide\/en\/elasticsearch\/(.+?)\/.+?\//,
`https://www.elastic.co/guide/en/elasticsearch/$1/${branch}/`
);
def.documentation = def.documentation
? def.documentation.replace(
/^https?:\/\/.+?\/guide\/en\/elasticsearch\/(.+?)\/.+?\//,
`https://www.elastic.co/guide/en/elasticsearch/$1/${branch}/`
)
: '';
var steps = name.split('.');
@ -222,27 +249,36 @@ module.exports = function (branch, done) {
var allParams = _.extend({}, def.url.params, def.url.parts);
_.forOwn(allParams, (paramSpec, paramName) => {
const toMerge = _.get(overrides, ['mergeConcatParams', name, paramName])
const toMerge = _.get(overrides, [
'mergeConcatParams',
name,
paramName,
]);
if (toMerge) {
_.mergeWith(paramSpec, toMerge, (dest, src) => {
if (_.isArray(dest) && _.isArray(src)) {
return dest.concat(src)
return dest.concat(src);
}
})
});
}
if (paramSpec.options) {
const invalidOpts = paramSpec.options.some(opt => typeof opt !== 'string')
if (invalidOpts) throw new Error(`${name} has options that are not strings...`)
const invalidOpts = paramSpec.options.some(
opt => typeof opt !== 'string'
);
if (invalidOpts)
throw new Error(`${name} has options that are not strings...`);
}
})
});
var spec = {
name: name,
methods: _.map(def.methods, function (m) { return m.toUpperCase(); }),
methods: _.map(def.methods, function(m) {
return m.toUpperCase();
}),
params: def.url.params,
body: def.body || null,
path2lib: utils.repeat('../', steps.length + 1) + 'lib/'
path2lib: utils.repeat('../', steps.length + 1) + 'lib/',
};
if (def.body && def.body.required) {
@ -255,63 +291,83 @@ module.exports = function (branch, done) {
var urls = _.difference(def.url.paths, overrides.aliases[name]);
var urlSignatures = [];
urls = _.map(urls, function (url) {
urls = _.map(urls, function(url) {
var optionalVars = {};
var requiredVars = {};
var param;
var name;
var target;
var match;
if (url.charAt(0) !== '/') {
url = '/' + url;
}
while (match = urlParamRE.exec(url)) {
while (true) {
const match = urlParamRE.exec(url);
if (!match) {
break;
}
name = utils.camelCase(match[1]);
param = def.url.parts[name] || {};
target = (param.required || !param.default) ? requiredVars : optionalVars;
target =
param.required || !param.default ? requiredVars : optionalVars;
target[name] = _.omit(param, ['required', 'description', 'name']);
}
urlSignatures.push(_.union(_.keys(optionalVars), _.keys(requiredVars)).sort().join(':'));
urlSignatures.push(
_.union(_.keys(optionalVars), _.keys(requiredVars))
.sort()
.join(':')
);
return _.omitBy({
fmt: url.replace(urlParamRE, function (full, match) {
return '<%=' + utils.camelCase(match) + '%>';
}),
opt: _.size(optionalVars) ? optionalVars : null,
req: _.size(requiredVars) ? requiredVars : null,
sortOrder: _.size(requiredVars) * -1
}, function (v) {
return !v;
});
return _.omitBy(
{
fmt: url.replace(urlParamRE, function(full, match) {
return '<%=' + utils.camelCase(match) + '%>';
}),
opt: _.size(optionalVars) ? optionalVars : null,
req: _.size(requiredVars) ? requiredVars : null,
sortOrder: _.size(requiredVars) * -1,
},
function(v) {
return !v;
}
);
});
if (urlSignatures.length !== _.uniq(urlSignatures).length) {
throw new Error(
'Multiple URLS with the same signature detected for ' +
spec.name +
'\n' +
_.map(urls, 'fmt').join('\n') +
'\n'
spec.name +
'\n' +
_.map(urls, 'fmt').join('\n') +
'\n'
);
}
if (urls.length > 1) {
spec.urls = _.map(_.sortBy(urls, 'sortOrder'), function (url) {
spec.urls = _.map(_.sortBy(urls, 'sortOrder'), function(url) {
return _.omit(url, 'sortOrder');
});
} else {
spec.url = _.omit(urls[0], 'sortOrder');
}
spec.params = _.transform(spec.params, function (note, param, name) {
// param.name = name;
note[name] = _.pick(param, [
'type', 'default', 'options', 'required', 'name'
]);
}, {});
spec.params = _.transform(
spec.params,
function(note, param, name) {
// param.name = name;
note[name] = _.pick(param, [
'type',
'default',
'options',
'required',
'name',
]);
},
{}
);
if (overrides.paramAsBody[name]) {
spec.paramAsBody = overrides.paramAsBody[name];
@ -322,8 +378,10 @@ module.exports = function (branch, done) {
}
// escape method names with "special" keywords
var location = spec.name.split('.').join('.prototype.')
.replace(/(^|\.)(delete|default)(\.|$)/g, '[\'$2\']');
var location = spec.name
.split('.')
.join('.prototype.')
.replace(/(^|\.)(delete|default)(\.|$)/g, "['$2']");
var action = {
_methods: spec.methods,
@ -334,13 +392,16 @@ module.exports = function (branch, done) {
'needBody',
'requestTimeout',
'bulkBody',
'paramAsBody'
'paramAsBody',
]),
location: location,
docUrl: def.documentation,
name: spec.name,
namespace: spec.name.split('.').slice(0, -1).join('.'),
allParams: allParams
namespace: spec.name
.split('.')
.slice(0, -1)
.join('.'),
allParams: allParams,
};
function hasMethod(/* ...methods */) {
@ -354,7 +415,10 @@ module.exports = function (branch, done) {
return true;
}
function methodsAre(/* ...methods */) {
return hasMethod.apply(null, arguments) && arguments.length === action._methods.length;
return (
hasMethod.apply(null, arguments) &&
arguments.length === action._methods.length
);
}
var method;
@ -365,17 +429,13 @@ module.exports = function (branch, done) {
// we need to define what the default method(s) will be
if (hasMethod('DELETE', 'POST')) {
method = 'POST';
}
else if (methodsAre('DELETE')) {
} else if (methodsAre('DELETE')) {
method = 'DELETE';
}
else if (methodsAre('POST', 'PUT')) {
} else if (methodsAre('POST', 'PUT')) {
method = action.name.match(/put/i) ? 'PUT' : 'POST';
}
else if (methodsAre('GET', 'POST')) {
} else if (methodsAre('GET', 'POST')) {
method = 'POST';
}
else if (methodsAre('GET', 'HEAD')) {
} else if (methodsAre('GET', 'HEAD')) {
method = 'GET';
}
}
@ -385,7 +445,9 @@ module.exports = function (branch, done) {
action.spec.method = method;
}
} else {
throw new Error('unable to pick a method for ' + JSON.stringify(action, null, ' '));
throw new Error(
'unable to pick a method for ' + JSON.stringify(action, null, ' ')
);
}
actions.push(action);

View File

@ -4,7 +4,7 @@ module.exports = [
paramAsBody: {
scroll: 'scrollId',
clearScroll: 'scrollId',
}
},
},
{
version: '0.90.x',
@ -15,7 +15,7 @@ module.exports = [
'/_nodes/hot_threads',
'/_cluster/nodes/{node_id}/hotthreads',
'/_cluster/nodes/{node_id}/hot_threads',
'/_nodes/{node_id}/hot_threads'
'/_nodes/{node_id}/hot_threads',
],
'cluster.nodeInfo': [
'/_cluster/nodes',
@ -37,25 +37,19 @@ module.exports = [
'/_nodes/{node_id}/network',
'/_nodes/{node_id}/transport',
'/_nodes/{node_id}/http',
'/_nodes/{node_id}/plugin'
],
'cluster.nodeShutdown': [
'/_cluster/nodes/_shutdown'
'/_nodes/{node_id}/plugin',
],
'cluster.nodeShutdown': ['/_cluster/nodes/_shutdown'],
'cluster.nodeStats': [
'/_cluster/nodes/stats',
'/_nodes/stats/{metric_family}',
'/_nodes/stats/indices/{metric}/{fields}',
'/_cluster/nodes/{node_id}/stats',
'/_nodes/{node_id}/stats/{metric_family}',
'/_nodes/{node_id}/stats/indices/{metric}/{fields}'
],
'get': [
'/{index}/{type}/{id}/_source'
],
'indices.deleteMapping': [
'/{index}/{type}/_mapping'
'/_nodes/{node_id}/stats/indices/{metric}/{fields}',
],
get: ['/{index}/{type}/{id}/_source'],
'indices.deleteMapping': ['/{index}/{type}/_mapping'],
'indices.stats': [
'_stats/{metric_family}',
'/_stats/indexing',
@ -65,9 +59,9 @@ module.exports = [
'/{index}/_stats/{metric_family}',
'/{index}/_stats/indexing',
'/{index}/_stats/search/{search_groups}',
'/{index}/_stats/fielddata/{fields}'
]
}
'/{index}/_stats/fielddata/{fields}',
],
},
},
{
version: '>=1.0.0',
@ -78,7 +72,7 @@ module.exports = [
'/_nodes/hot_threads',
'/_cluster/nodes/{node_id}/hotthreads',
'/_cluster/nodes/{node_id}/hot_threads',
'/_nodes/{node_id}/hot_threads'
'/_nodes/{node_id}/hot_threads',
],
'nodes.info': [
'/_cluster/nodes',
@ -100,27 +94,23 @@ module.exports = [
'/_nodes/{node_id}/network',
'/_nodes/{node_id}/transport',
'/_nodes/{node_id}/http',
'/_nodes/{node_id}/plugin'
],
'nodes.shutdown': [
'/_cluster/nodes/_shutdown'
'/_nodes/{node_id}/plugin',
],
'nodes.shutdown': ['/_cluster/nodes/_shutdown'],
'nodes.stats': [
'/_cluster/nodes/stats',
'/_nodes/stats/{metric_family}',
'/_nodes/stats/indices/{metric}/{fields}',
'/_cluster/nodes/{node_id}/stats',
'/_nodes/{node_id}/stats/{metric_family}',
'/_nodes/{node_id}/stats/indices/{metric}/{fields}'
],
'get': [
'/{index}/{type}/{id}/_source'
'/_nodes/{node_id}/stats/indices/{metric}/{fields}',
],
get: ['/{index}/{type}/{id}/_source'],
'indices.deleteMapping': [
'/{index}/{type}',
'/{index}/_mapping/{type}',
'/{index}/{type}/_mappings',
'/{index}/_mappings/{type}'
'/{index}/_mappings/{type}',
],
'indices.putWarmer': [
// '/_warmer/{name}',
@ -128,23 +118,23 @@ module.exports = [
// '/{index}/{type}/_warmer/{name}',
'/_warmers/{name}',
'/{index}/_warmers/{name}',
'/{index}/{type}/_warmers/{name}'
'/{index}/{type}/_warmers/{name}',
],
'indices.deleteWarmer': [
// '/{index}/_warmer/{name}',
'/{index}/_warmer',
'/{index}/_warmers',
'/{index}/_warmers/{name}'
'/{index}/_warmers/{name}',
],
'indices.deleteAlias': [
// '/{index}/_alias/{name}',
'/{index}/_aliases/{name}'
'/{index}/_aliases/{name}',
],
'indices.putAlias': [
// '/{index}/_alias/{name}',
// '/_alias/{name}',
'/{index}/_aliases/{name}',
'/_aliases/{name}'
'/_aliases/{name}',
],
'indices.putMapping': [
// '/{index}/_mapping/{type}',
@ -154,7 +144,7 @@ module.exports = [
'/{index}/{type}/_mappings',
'/{index}/_mappings/{type}',
'/{index}/_mappings',
'/_mappings/{type}'
'/_mappings/{type}',
],
'indices.stats': [
'_stats/{metric_family}',
@ -165,31 +155,29 @@ module.exports = [
'/{index}/_stats/{metric_family}',
'/{index}/_stats/indexing',
'/{index}/_stats/search/{search_groups}',
'/{index}/_stats/fielddata/{fields}'
]
}
'/{index}/_stats/fielddata/{fields}',
],
},
},
{
version: '>1.4.0',
aliases: {
'indices.putAlias': [
// '/{index}/_alias/{name}',
'/{index}/_aliases/{name}'
]
}
'/{index}/_aliases/{name}',
],
},
},
{
version: '<1.6.0',
aliases: {
'snapshot.create': [
'/_snapshot/{repository}/{snapshot}'
]
}
'snapshot.create': ['/_snapshot/{repository}/{snapshot}'],
},
},
{
version: '>=1.6.0',
// strange indentation makes pretty api files
// strange indentation makes pretty api files
/* eslint-disable */
clientActionModifier:
function (spec) {
@ -202,95 +190,92 @@ function (spec) {
}
});
}
/* eslint-enable */
/* eslint-enable */
},
{
version: '>=2.0.0',
aliases: {
'reindex.rethrottle': [
'/_update_by_query/{task_id}/_rethrottle',
'/_delete_by_query/{task_id}/_rethrottle'
'/_delete_by_query/{task_id}/_rethrottle',
],
'reindexRethrottle': [
'/_update_by_query/{task_id}/_rethrottle'
]
}
reindexRethrottle: ['/_update_by_query/{task_id}/_rethrottle'],
},
},
{
version: '>=5.0.0',
mergeConcatParams: {
bulk: {
refresh: {
options: ['']
}
options: [''],
},
},
create: {
refresh: {
options: ['']
}
options: [''],
},
},
index: {
refresh: {
options: ['']
}
options: [''],
},
},
update: {
refresh: {
options: ['']
}
options: [''],
},
},
delete: {
refresh: {
options: ['']
}
}
options: [''],
},
},
},
aliases: {
'reindexRethrottle': [
reindexRethrottle: [
'/_update_by_query/{task_id}/_rethrottle',
'/_delete_by_query/{task_id}/_rethrottle'
]
}
'/_delete_by_query/{task_id}/_rethrottle',
],
},
},
{
version: '>=2.0',
paramAsBody: {
scroll: {
param: 'scrollId',
body: 'scroll_id'
body: 'scroll_id',
},
clearScroll: {
param: 'scrollId',
body: 'scroll_id'
}
}
body: 'scroll_id',
},
},
},
// description overrides by major version
{
version: '0.90.x',
descriptions: {
search: 'search_1.x.asciidoc'
}
search: 'search_1.x.asciidoc',
},
},
{
version: '1.x',
descriptions: {
search: 'search_1.x.asciidoc'
}
search: 'search_1.x.asciidoc',
},
},
{
version: '2.x',
descriptions: {
search: 'search_2.x.asciidoc'
}
search: 'search_2.x.asciidoc',
},
},
// examples changed at 5.0
{
version: '<5.0.0',
examples: {
scroll: 'scroll_<5.0.asciidoc'
}
scroll: 'scroll_<5.0.asciidoc',
},
},
{
version: '>=5.2 <5.5',
@ -299,7 +284,7 @@ function (spec) {
param: 'scrollId',
body: 'scroll_id',
castToArray: true,
}
}
}
},
},
},
];

View File

@ -16,7 +16,7 @@ WARNING: Due to the complex nature of the configuration, the config object you p
[[config-options]]
=== Config options
[horizontal]
`host or hosts`[[config-hosts]]::
[[config-hosts]]`host or hosts`::
`String, String[], Object[]` -- Specify the hosts that this client will connect to. If sniffing is enabled, or you call `client.sniff()`, this list will be used as seeds to discover the rest of your cluster.
+
The value(s) are passed to the <<host-reference,`Host`>> constructor. `Host` objects can help enforce path-prefixes, default headers and query strings, and can be helpful in making more intelligent selection algorithms; Head over to <<host-reference,the `Host` docs>> for more information.
@ -29,7 +29,7 @@ Default:::
------
`httpAuth`[[config-http-auth]]:: `String` -- Specifies the default http auth as a String with username and password separated by a colon (eg. `user:pass`). Applies to any host defined in the original config, and any hosts discovered while sniffing.
[[config-http-auth]]`httpAuth`:: `String` -- Specifies the default http auth as a String with username and password separated by a colon (eg. `user:pass`). Applies to any host defined in the original config, and any hosts discovered while sniffing.
`log`[[config-log]]:: `String, String[], Object, Object[], Constructor` -- Unless a constructor is specified, this sets the output settings for the bundled logger. See the section on configuring-logging[logging] for more information.
@ -48,7 +48,7 @@ Default in Node:::
`apiVersion`[[config-api-version]]:: `String` -- Change the API that they client provides, specify the major version of the Elasticsearch nodes you will be connecting to.
[[config-api-version]]`apiVersion`:: `String` -- Change the API that they client provides, specify the major version of the Elasticsearch nodes you will be connecting to.
+
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.
@ -70,7 +70,7 @@ Options in the browser :::
<% 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`.
[[config-plugins]]`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`.
+
`Constructor` is the class that will be newed up to create the client instance. It's prototype contains the api methods that correlate to the `apiVersion` requested.
+
@ -79,7 +79,7 @@ Options in the browser :::
`components` is a map of the internal classes for this version of the elasticsearch client. The values on this object are listed https://github.com/elastic/elasticsearch-js/blob/master/src/lib/client.js#L80[here].
`sniffOnStart`[[config-sniff-on-start]]:: `Boolean` -- Should the client attempt to detect the rest of the cluster when it is first instantiated?
[[config-sniff-on-start]]`sniffOnStart`:: `Boolean` -- Should the client attempt to detect the rest of the cluster when it is first instantiated?
Default::: `false`
@ -87,7 +87,7 @@ Default::: `false`
`sniffInterval`[[config-sniff-interval]]:: `Number, false` -- Every `n` milliseconds, perform a sniff operation and make sure our list of nodes is complete.
[[config-sniff-interval]]`sniffInterval`:: `Number, false` -- Every `n` milliseconds, perform a sniff operation and make sure our list of nodes is complete.
Default::: `false`
@ -95,14 +95,14 @@ Default::: `false`
`sniffOnConnectionFault`[[config-sniff-on-connection-fault]]:: `Boolean` -- Should the client immediately sniff for a more current list of nodes when a connection dies?
[[config-sniff-on-connection-fault]]`sniffOnConnectionFault`:: `Boolean` -- Should the client immediately sniff for a more current list of nodes when a connection dies?
Default::: `false`
`maxRetries`[[config-max-retries]]:: `Integer` -- How many times should the client try to connect to other nodes before returning a <<connection-fault,ConnectionFault>> error.
[[config-max-retries]]`maxRetries`:: `Integer` -- How many times should the client try to connect to other nodes before returning a <<connection-fault,ConnectionFault>> error.
Default::: `3`
@ -110,7 +110,7 @@ Default::: `3`
`requestTimeout`[[config-request-timeout]]:: `Number` -- Milliseconds before an HTTP request will be aborted and retried. This can also be set per request.
[[config-request-timeout]]`requestTimeout`:: `Number` -- Milliseconds before an HTTP request will be aborted and retried. This can also be set per request.
Default::: `30000`
@ -118,47 +118,47 @@ Default::: `30000`
`deadTimeout`[[config-dead-timeout]]:: `Number` -- Milliseconds that a dead connection will wait before attempting to revive itself.
[[config-dead-timeout]]`deadTimeout`:: `Number` -- Milliseconds that a dead connection will wait before attempting to revive itself.
Default::: `60000`
`pingTimeout`[[config-ping-timeout]]:: `Number` -- Milliseconds that a ping request can take before timing out.
[[config-ping-timeout]]`pingTimeout`:: `Number` -- Milliseconds that a ping request can take before timing out.
Default::: `3000`
`maxSockets`[[config-keep-alive-max-sockets]]:: `Number` -- Maximum number of sockets to allow per host.
[[config-keep-alive-max-sockets]]`maxSockets`:: `Number` -- Maximum number of sockets to allow per host.
Default::: `Infinity`
`keepAlive`[[config-keep-alive]]:: `Boolean` -- Should the connections to the node be kept open forever? This behavior is recommended when you are connecting directly to Elasticsearch.
[[config-keep-alive]]`keepAlive`:: `Boolean` -- Should the connections to the node be kept open forever? This behavior is recommended when you are connecting directly to Elasticsearch.
Default::: `true`
`keepAliveInterval`[[config-keep-alive-interval]]:: `Number` -- How often, in milliseconds, should TCP KeepAlive packets be sent over sockets being kept alive. Only relevant if `keepAlive` is set to `true`.
[[config-keep-alive-interval]]`keepAliveInterval`:: `Number` -- How often, in milliseconds, should TCP KeepAlive packets be sent over sockets being kept alive. Only relevant if `keepAlive` is set to `true`.
Default::: `1000`
`keepAliveMaxFreeSockets`[[config-keep-alive-max-free-sockets]]:: `Number` -- Maximum number of inactive sockets to keep connected to a node. Only relevant if `keepAlive` is set to `true`.
[[config-keep-alive-max-free-sockets]]`keepAliveMaxFreeSockets`:: `Number` -- Maximum number of inactive sockets to keep connected to a node. Only relevant if `keepAlive` is set to `true`.
Default::: `256`
`keepAliveFreeSocketTimeout`[[config-keep-alive-free-socket-timeout]]:: `Number` -- Sets inactive sockets to timeout after milliseconds of inactivity. Only relevant if `keepAlive` is set to `true`.
[[config-keep-alive-free-socket-timeout]]`keepAliveFreeSocketTimeout`:: `Number` -- Sets inactive sockets to timeout after milliseconds of inactivity. Only relevant if `keepAlive` is set to `true`.
Default::: `60000`
`suggestCompression`[[config-suggest-compression]]:: `Boolean` -- The client should inform Elasticsearch, on each request, that it can accept compressed responses. In order for the responses to actually be compressed, you must enable `http.compression` in Elasticsearch. See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-http.html[these docs] for additional info.
[[config-suggest-compression]]`suggestCompression`:: `Boolean` -- The client should inform Elasticsearch, on each request, that it can accept compressed responses. In order for the responses to actually be compressed, you must enable `http.compression` in Elasticsearch. See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-http.html[these docs] for additional info.
Default::: `false`
`connectionClass`[[config-connection-class]]:: `String, Constructor` -- Defines the class that will be used to create connections to store in the connection pool. If you are looking to implement additional protocols you should probably start by writing a Connection class that extends the ConnectionAbstract.
[[config-connection-class]]`connectionClass`:: `String, Constructor` -- Defines the class that will be used to create connections to store in the connection pool. If you are looking to implement additional protocols you should probably start by writing a Connection class that extends the ConnectionAbstract.
Defaults:::
* Node: `"http"`
@ -167,12 +167,12 @@ Defaults:::
* jQuery Build: `"jquery"`
`sniffedNodesProtocol`[[config-sniffed-nodes-protocol]]:: `String` -- Defines the protocol that will be used to communicate with nodes discovered during sniffing.
[[config-sniffed-nodes-protocol]]`sniffedNodesProtocol`:: `String` -- Defines the protocol that will be used to communicate with nodes discovered during sniffing.
Default::: If all of the hosts/host passed to the client via configuration use the same protocol then this defaults to that protocol, otherwise it defaults to `"http"`.
`ssl`[[config-ssl]]:: `Object` -- An object defining HTTPS/SSL configuration to use for all nodes. The properties of this mimic the options accepted by http://nodejs.org/docs/latest/api/tls.html#tls_tls_connect_port_host_options_callback[`tls.connect()`] with the exception of `rejectUnauthorized`, which defaults to `false` allowing self-signed certificates to work out-of-the-box.
[[config-ssl]]`ssl`:: `Object` -- An object defining HTTPS/SSL configuration to use for all nodes. The properties of this mimic the options accepted by http://nodejs.org/docs/latest/api/tls.html#tls_tls_connect_port_host_options_callback[`tls.connect()`] with the exception of `rejectUnauthorized`, which defaults to `false` allowing self-signed certificates to work out-of-the-box.
+
Additional information available in <<auth-reference>>.
@ -202,7 +202,7 @@ var client = new elasticsearch.Client({
-----
`selector`[[config-selector]]:: `String, Function` -- This function will be used to select a connection from the ConnectionPool. It should received a single argument, the list of "active" connections, and return the connection to use. Use this selector to implement special logic for your client such as preferring nodes in a certain rack or data-center.
[[config-selector]]`selector`:: `String, Function` -- This function will be used to select a connection from the ConnectionPool. It should received a single argument, the list of "active" connections, and return the connection to use. Use this selector to implement special logic for your client such as preferring nodes in a certain rack or data-center.
+
To make this function asynchronous, accept a second argument which will be the callback to use. The callback should be called Node-style with a possible error like: `cb(err, selectedConnection)`.
@ -216,7 +216,7 @@ Options:::
`defer`[[config-defer]]:: `Function` -- Override the way that the client creates promises. If you would rather use any other promise library this is how you'd do that. Elasticsearch.js expects that the defer object has a `promise` property (which will be returned to promise consumers), as well as `resolve` and `reject` methods.
[[config-defer]]`defer`:: `Function` -- Override the way that the client creates promises. If you would rather use any other promise library this is how you'd do that. Elasticsearch.js expects that the defer object has a `promise` property (which will be returned to promise consumers), as well as `resolve` and `reject` methods.
Default::: Defer object created with ES6 Promise
@ -234,7 +234,7 @@ var client = new elasticsearch.Client({
`nodesToHostCallback`[[config-nodes-to-host-callback]]:: `Function` - This function will receive the list of nodes returned from the `_cluster/nodes` API during a sniff operation. The function should return an array of objects which match the <<config-hosts,specification for the `hosts` config>>.
[[config-nodes-to-host-callback]]`nodesToHostCallback`:: `Function` - This function will receive the list of nodes returned from the `_cluster/nodes` API during a sniff operation. The function should return an array of objects which match the <<config-hosts,specification for the `hosts` config>>.
Default:::
see https://github.com/elasticsearch/elasticsearch-js/blob/master/src/lib/nodes_to_host.js[nodes_to_host.js]
@ -242,7 +242,7 @@ see https://github.com/elasticsearch/elasticsearch-js/blob/master/src/lib/nodes_
`createNodeAgent`[[config-create-node-agent]]:: `Function` -- Override the way that the client creates node.js `Agent`[https://nodejs.org/api/http.html#http_class_http_agent] objects. The value of this property will be executed every time a new Node is added to the client (either from the initial seed or from sniffing) and can return any value that node's http(s) module accepts as `agent:` configuration.
[[config-create-node-agent]]`createNodeAgent`:: `Function` -- Override the way that the client creates node.js `Agent`[https://nodejs.org/api/http.html#http_class_http_agent] objects. The value of this property will be executed every time a new Node is added to the client (either from the initial seed or from sniffing) and can return any value that node's http(s) module accepts as `agent:` configuration.
+
The function is called with two arguments, first an `HttpConnector`[http://github.com/spalger/elasticsearch-js/blob/master/src/lib/connectors/http.js] object and the second the config object initially passed when creating the client.

View File

@ -1,11 +1,9 @@
var _ = require('lodash');
var utils = require('../../../src/lib/utils');
var gruntUtils = require('../../../grunt/utils');
var fs = require('fs');
var path = require('path');
/**
* we want strings in code to use single-quotes, so this will JSON encode vars, but then
* modify them to follow our code standards.
@ -14,18 +12,20 @@ var path = require('path');
* @return {String} - our pretty string
*/
function stringify(thing, pretty) {
return (pretty ? JSON.stringify(thing, null, ' ') : JSON.stringify(thing))
.replace(/'/g, '\\\'')
.replace(/\\?"/g, function (quote) {
// replace external (unescaped) double quotes with single quotes
return quote === '\\"' ? '"' : '\'';
})
// inject a space between STRING array parts
.replace(/([^\\])','/g, '$1\', \'')
// remove quotes around key names that are only made up of letters
.replace(/^( +)'([a-zA-Z_]+)':/gm, '$1$2:')
// requote "special" key names
.replace(/^( +)(default):/gm, '$1\'$2\':');
return (
(pretty ? JSON.stringify(thing, null, ' ') : JSON.stringify(thing))
.replace(/'/g, "\\'")
.replace(/\\?"/g, function(quote) {
// replace external (unescaped) double quotes with single quotes
return quote === '\\"' ? '"' : "'";
})
// inject a space between STRING array parts
.replace(/([^\\])','/g, "$1', '")
// remove quotes around key names that are only made up of letters
.replace(/^( +)'([a-zA-Z_]+)':/gm, '$1$2:')
// requote "special" key names
.replace(/^( +)(default):/gm, "$1'$2':")
);
}
/**
@ -39,28 +39,30 @@ var templates = {};
* @type {Object}
*/
var templateGlobals = {
stringify: stringify,
_: _,
utils: utils,
indent: function (block, spaces) {
indent: function(block, spaces) {
var indent = utils.repeat(' ', spaces);
return block.split('\n').map(function (line) {
return indent + line;
}).join('\n');
return block
.split('\n')
.map(function(line) {
return indent + line;
})
.join('\n');
},
joinParagraphs: function (block) {
joinParagraphs: function(block) {
return block.split('\n\n').join('\n+\n');
},
paramType: function (type, paramName) {
paramType: function(type, paramName) {
switch (type && type.toLowerCase ? type.toLowerCase() : 'any') {
case 'time':
case 'duration':
if (paramName === 'timestamp') return 'Timestamp'
if (paramName === 'timestamp') return 'Timestamp';
return '<<api-param-type-duration-string,`DurationString`>>';
case 'any':
return 'anything';
@ -84,7 +86,7 @@ var templateGlobals = {
}
},
paramWithDefault: function (name, def) {
paramWithDefault: function(name, def) {
if (def) {
return '[' + name + '=' + def + ']';
} else {
@ -94,16 +96,16 @@ var templateGlobals = {
partials: templates,
gruntUtils: gruntUtils
gruntUtils: gruntUtils,
};
fs.readdirSync(path.resolve(__dirname)).forEach(function (filename) {
fs.readdirSync(path.resolve(__dirname)).forEach(function(filename) {
var name = filename.replace(/\..+$/, '');
if (name !== 'index') {
templates[name] = _.template(
fs.readFileSync(path.resolve(__dirname, filename), 'utf8'),
{
imports: templateGlobals
imports: templateGlobals,
}
);
}

View File

@ -1,58 +0,0 @@
module.exports = function (branch, done) {
/**
* Creates a JSON version of the YAML test suite that can be simply bundled for use in the browser.
*/
var jsYaml = require('js-yaml');
var fs = require('fs');
var async = require('async');
var chalk = require('chalk');
var path = require('path');
var fromRoot = path.join.bind(path, require('find-root')(__dirname));
var utils = require(fromRoot('src/lib/utils'));
var tests = {}; // populated in readYamlTests
var esDir = fromRoot('src/_elasticsearch_' + utils.snakeCase(branch));
// generate the yaml tests
async.series([
readYamlTests,
writeYamlTests,
writeTestIndex
], done);
function readYamlTests(done) {
var testDir = path.join(esDir, 'rest-api-spec/test/');
function readDirectories(dir) {
fs.readdirSync(dir).forEach(function (filename) {
var filePath = path.join(dir, filename);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
readDirectories(filePath);
} else if (filename.match(/\.yaml$/)) {
var file = tests[path.relative(testDir, filePath)] = [];
jsYaml.loadAll(fs.readFileSync(filePath, 'utf8'), function (doc) {
file.push(doc);
});
}
});
}
readDirectories(testDir);
done();
}
function writeYamlTests(done) {
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_' + utils.snakeCase(branch) + '.js');
fs.writeFileSync(file, 'require(\'./run\')(\'' + branch + '\');\n', 'utf8');
console.log(chalk.white.bold('wrote') + ' YAML index to', file);
done();
}
};

View File

@ -1,61 +0,0 @@
#!/bin/bash
export JAVA_HOME="/usr/lib/jvm/jdk8"
lockpath="/var/lock/setup_nodejs"
# pass a file name to aquire a lock
function get_lock {
echo "attempting to get a lock on $lockpath"
lockfile -5 -r 120 "$lockpath"
if [[ $? -gt 0 ]]; then
echo "failed to get lock file $lockpath within 10 minutes"
exit 1;
else
echo "acquired lock file $lockpath"
fi
}
# clear all aquired locks
function release_lock {
rm -f "$lockpath"
echo "cleared lock file $lockpath"
}
# execute a command, and exit if it fails
function crit {
$*
CODE=$?
if [[ $CODE -gt 0 ]]; then
echo "last command was critical, but it reported non-zero exit code $CODE";
release_lock # clear any locks
exit $CODE;
fi
}
# install a specific version of Node and the latest version of NPM within that install
function install_node {
local version=$1
if [[ $(type -t nvm) != "function" ]]; then
source /mnt/jenkins/nvm/nvm.sh
ulimit -c unlimited
fi
echo "installing node $version";
crit nvm install "$version"
if [[ "$(which npm)" == "" ]]; then
echo "npm is missing, reinstalling node version $version";
crit nvm deactivate;
crit nvm uninstall "$version";
install_node "$version";
return
fi
}
get_lock
install_node "$(cat ./.node-version)"
npm install
release_lock
ES_PATH_REPO="./.es-snapshot-repos/$EXECUTOR_NUMBER/" ES_PORT=$((9400 + EXECUTOR_NUMBER)) RUN=NODE_UNIT,NODE_INTEGRATION VERBOSE=true node ./scripts/ci.js

7
scripts/mocha.js Normal file
View File

@ -0,0 +1,7 @@
process.argv.splice(
2,
0,
...[require.resolve('../test/unit/index.js'), '--reporter', 'nyan']
);
require('mocha/bin/mocha');

View File

@ -16,30 +16,45 @@ bowerJson.version = esjsJson.version;
bowerPackageJson.version = esjsJson.version;
// write the new bower.json file
fs.writeFileSync(bowerDir + '/bower.json', JSON.stringify(bowerJson, null, ' '));
fs.writeFileSync(
bowerDir + '/bower.json',
JSON.stringify(bowerJson, null, ' ')
);
// write the new package.json file
fs.writeFileSync(bowerDir + '/package.json', JSON.stringify(bowerPackageJson, null, ' '));
fs.writeFileSync(
bowerDir + '/package.json',
JSON.stringify(bowerPackageJson, null, ' ')
);
function make(cmd, args) {
return _.bind(spawn, null, cmd, args, {
verbose: true,
cwd: bowerDir
cwd: bowerDir,
});
}
async.series([
make('git', ['add', '-A']),
make('git', ['commit', '-m', 'version ' + bowerJson.version]),
make('git', ['tag', '-a', 'v' + bowerJson.version, '-m', 'version ' + bowerJson.version]),
make('git', ['push', 'origin', 'master']),
make('git', ['push', '--tags', 'origin']),
make('npm', ['publish'])
], function (err) {
if (err) {
if (_.isNumber(err)) {
console.log('Non-zero exit code: %d', err);
} else {
console.log('Error: ', err.message ? err.message : err);
async.series(
[
make('git', ['add', '-A']),
make('git', ['commit', '-m', 'version ' + bowerJson.version]),
make('git', [
'tag',
'-a',
'v' + bowerJson.version,
'-m',
'version ' + bowerJson.version,
]),
make('git', ['push', 'origin', 'master']),
make('git', ['push', '--tags', 'origin']),
make('npm', ['publish']),
],
function(err) {
if (err) {
if (_.isNumber(err)) {
console.log('Non-zero exit code: %d', err);
} else {
console.log('Error: ', err.message ? err.message : err);
}
}
}
});
);

View File

@ -10,14 +10,15 @@ var Client = require('./lib/client');
process.angular_build = true;
/* 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();
};
config.serializer = config.serializer || 'angular';
@ -29,4 +30,5 @@ angular.module('elasticsearch', [])
factory.Transport = require('./lib/transport');
return factory;
}]);
},
]);

View File

@ -1,5 +1,5 @@
/* global jQuery */
(function ($) {
(function($) {
process.jquery_build = true;
var es = require('./elasticsearch');
@ -12,11 +12,10 @@
}
$.es = $.extend({}, es);
$.es.Client = function (config) {
$.es.Client = function(config) {
config = config || {};
config.defer = defer;
config.$ = $;
return new es.Client(config);
};
}(jQuery));
})(jQuery);

View File

@ -2,9 +2,11 @@
// throw an error when they try to instanciate the exported function.
// previous "elasticsearch" module -> https://github.com/ncb000gt/node-es
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)`.'
);
}
es.Client = require('./lib/client');

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -14,7 +14,7 @@ var api = module.exports = {};
api._namespaces = ['cat', 'cluster', 'indices', 'ingest', 'nodes', 'snapshot', 'tasks'];
/**
* Perform a [bulk](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-bulk.html) request
* Perform a [bulk](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-bulk.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.waitForActiveShards - Sets the number of shard copies that must be active before proceeding with the bulk operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
@ -103,7 +103,7 @@ api.bulk = ca({
api.cat = namespace();
/**
* Perform a [cat.aliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat.html) request
* Perform a [cat.aliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -158,7 +158,7 @@ api.cat.prototype.aliases = ca({
});
/**
* Perform a [cat.allocation](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-allocation.html) request
* Perform a [cat.allocation](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-allocation.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -230,7 +230,7 @@ api.cat.prototype.allocation = ca({
});
/**
* Perform a [cat.count](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-count.html) request
* Perform a [cat.count](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-count.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -285,7 +285,7 @@ api.cat.prototype.count = ca({
});
/**
* Perform a [cat.fielddata](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-fielddata.html) request
* Perform a [cat.fielddata](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-fielddata.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -360,7 +360,7 @@ api.cat.prototype.fielddata = ca({
});
/**
* Perform a [cat.health](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-health.html) request
* Perform a [cat.health](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-health.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -409,7 +409,7 @@ api.cat.prototype.health = ca({
});
/**
* Perform a [cat.help](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat.html) request
* Perform a [cat.help](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.help - Return help information
@ -431,7 +431,7 @@ api.cat.prototype.help = ca({
});
/**
* Perform a [cat.indices](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-indices.html) request
* Perform a [cat.indices](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-indices.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -511,7 +511,7 @@ api.cat.prototype.indices = ca({
});
/**
* Perform a [cat.master](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-master.html) request
* Perform a [cat.master](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-master.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -555,7 +555,7 @@ api.cat.prototype.master = ca({
});
/**
* Perform a [cat.nodeattrs](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-nodeattrs.html) request
* Perform a [cat.nodeattrs](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-nodeattrs.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -599,7 +599,7 @@ api.cat.prototype.nodeattrs = ca({
});
/**
* Perform a [cat.nodes](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-nodes.html) request
* Perform a [cat.nodes](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-nodes.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -648,7 +648,7 @@ api.cat.prototype.nodes = ca({
});
/**
* Perform a [cat.pendingTasks](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-pending-tasks.html) request
* Perform a [cat.pendingTasks](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-pending-tasks.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -692,7 +692,7 @@ api.cat.prototype.pendingTasks = ca({
});
/**
* Perform a [cat.plugins](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-plugins.html) request
* Perform a [cat.plugins](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-plugins.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -736,7 +736,7 @@ api.cat.prototype.plugins = ca({
});
/**
* Perform a [cat.recovery](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-recovery.html) request
* Perform a [cat.recovery](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-recovery.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -804,7 +804,7 @@ api.cat.prototype.recovery = ca({
});
/**
* Perform a [cat.repositories](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-repositories.html) request
* Perform a [cat.repositories](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-repositories.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -849,7 +849,7 @@ api.cat.prototype.repositories = ca({
});
/**
* Perform a [cat.segments](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-segments.html) request
* Perform a [cat.segments](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-segments.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -912,7 +912,7 @@ api.cat.prototype.segments = ca({
});
/**
* Perform a [cat.shards](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-shards.html) request
* Perform a [cat.shards](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-shards.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -984,7 +984,7 @@ api.cat.prototype.shards = ca({
});
/**
* Perform a [cat.snapshots](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-snapshots.html) request
* Perform a [cat.snapshots](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -1041,7 +1041,7 @@ api.cat.prototype.snapshots = ca({
});
/**
* Perform a [cat.tasks](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/tasks.html) request
* Perform a [cat.tasks](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/tasks.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -1094,7 +1094,7 @@ api.cat.prototype.tasks = ca({
});
/**
* Perform a [cat.templates](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-templates.html) request
* Perform a [cat.templates](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-templates.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -1149,7 +1149,7 @@ api.cat.prototype.templates = ca({
});
/**
* Perform a [cat.threadPool](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cat-thread-pool.html) request
* Perform a [cat.threadPool](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cat-thread-pool.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.format - a short version of the Accept header, e.g. json, yaml
@ -1216,7 +1216,7 @@ api.cat.prototype.threadPool = ca({
});
/**
* Perform a [clearScroll](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-request-scroll.html) request
* Perform a [clearScroll](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-scroll.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.scrollId - A comma-separated list of scroll IDs to clear
@ -1245,7 +1245,7 @@ api.clearScroll = ca({
api.cluster = namespace();
/**
* Perform a [cluster.allocationExplain](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-allocation-explain.html) request
* Perform a [cluster.allocationExplain](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-allocation-explain.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeYesDecisions - Return 'YES' decisions in explanation (default: false)
@ -1269,7 +1269,7 @@ api.cluster.prototype.allocationExplain = ca({
});
/**
* Perform a [cluster.getSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-update-settings.html) request
* Perform a [cluster.getSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-update-settings.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.flatSettings - Return settings in flat format (default: false)
@ -1302,7 +1302,7 @@ api.cluster.prototype.getSettings = ca({
});
/**
* Perform a [cluster.health](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-health.html) request
* Perform a [cluster.health](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-health.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} [params.level=cluster] - Specify the level of detail for returned information
@ -1393,7 +1393,7 @@ api.cluster.prototype.health = ca({
});
/**
* Perform a [cluster.pendingTasks](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-pending.html) request
* Perform a [cluster.pendingTasks](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-pending.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.local - Return local information, do not retrieve the state from master node (default: false)
@ -1415,7 +1415,7 @@ api.cluster.prototype.pendingTasks = ca({
});
/**
* Perform a [cluster.putSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-update-settings.html) request
* Perform a [cluster.putSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-update-settings.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.flatSettings - Return settings in flat format (default: false)
@ -1444,7 +1444,7 @@ api.cluster.prototype.putSettings = ca({
});
/**
* Perform a [cluster.remoteInfo](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-remote-info.html) request
* Perform a [cluster.remoteInfo](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-remote-info.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
*/
@ -1455,7 +1455,7 @@ api.cluster.prototype.remoteInfo = ca({
});
/**
* Perform a [cluster.reroute](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-reroute.html) request
* Perform a [cluster.reroute](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-reroute.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.dryRun - Simulate the operation only and return the resulting state
@ -1505,7 +1505,7 @@ api.cluster.prototype.reroute = ca({
});
/**
* Perform a [cluster.state](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-state.html) request
* Perform a [cluster.state](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-state.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.local - Return local information, do not retrieve the state from master node (default: false)
@ -1607,7 +1607,7 @@ api.cluster.prototype.state = ca({
});
/**
* Perform a [cluster.stats](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-stats.html) request
* Perform a [cluster.stats](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-stats.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.flatSettings - Return settings in flat format (default: false)
@ -1640,7 +1640,7 @@ api.cluster.prototype.stats = ca({
});
/**
* Perform a [count](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-count.html) request
* Perform a [count](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-count.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -1753,7 +1753,7 @@ api.count = ca({
});
/**
* Perform a [create](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-index_.html) request
* Perform a [create](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-index_.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.waitForActiveShards - Sets the number of shard copies that must be active before proceeding with the index operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
@ -1828,7 +1828,7 @@ api.create = ca({
});
/**
* Perform a [delete](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-delete.html) request
* Perform a [delete](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-delete.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.waitForActiveShards - Sets the number of shard copies that must be active before proceeding with the delete operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
@ -1908,7 +1908,7 @@ api['delete'] = ca({
});
/**
* Perform a [deleteByQuery](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-delete-by-query.html) request
* Perform a [deleteByQuery](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-delete-by-query.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.analyzer - The analyzer to use for the query string
@ -2111,7 +2111,7 @@ api.deleteByQuery = ca({
});
/**
* Perform a [deleteByQueryRethrottle](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-delete-by-query.html) request
* Perform a [deleteByQueryRethrottle](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-delete-by-query.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-number,`Number`>>} params.requestsPerSecond - The throttle to set on this request in floating sub-requests per second. -1 means set no throttle.
@ -2137,7 +2137,7 @@ api.deleteByQueryRethrottle = ca({
});
/**
* Perform a [deleteScript](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-scripting.html) request
* Perform a [deleteScript](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-scripting.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -2166,7 +2166,7 @@ api.deleteScript = ca({
});
/**
* Perform a [exists](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-get.html) request
* Perform a [exists](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-get.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.storedFields - A comma-separated list of stored fields to return in the response
@ -2248,7 +2248,7 @@ api.exists = ca({
});
/**
* Perform a [existsSource](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-get.html) request
* Perform a [existsSource](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-get.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.parent - The ID of the parent document
@ -2325,7 +2325,7 @@ api.existsSource = ca({
});
/**
* Perform a [explain](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-explain.html) request
* Perform a [explain](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-explain.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false)
@ -2415,7 +2415,7 @@ api.explain = ca({
});
/**
* Perform a [fieldCaps](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-field-caps.html) request
* Perform a [fieldCaps](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-field-caps.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.fields - A comma-separated list of field names
@ -2466,7 +2466,7 @@ api.fieldCaps = ca({
});
/**
* Perform a [get](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-get.html) request
* Perform a [get](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-get.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.storedFields - A comma-separated list of stored fields to return in the response
@ -2557,7 +2557,7 @@ api.get = ca({
});
/**
* Perform a [getScript](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-scripting.html) request
* Perform a [getScript](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-scripting.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Specify timeout for connection to master
@ -2581,7 +2581,7 @@ api.getScript = ca({
});
/**
* Perform a [getSource](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-get.html) request
* Perform a [getSource](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-get.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.parent - The ID of the parent document
@ -2657,7 +2657,7 @@ api.getSource = ca({
});
/**
* Perform a [index](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-index_.html) request
* Perform a [index](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-index_.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.waitForActiveShards - Sets the number of shard copies that must be active before proceeding with the index operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
@ -2767,7 +2767,7 @@ api.index = ca({
api.indices = namespace();
/**
* Perform a [indices.analyze](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-analyze.html) request
* Perform a [indices.analyze](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-analyze.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.index - The name of the index to scope the operation
@ -2795,7 +2795,7 @@ api.indices.prototype.analyze = ca({
});
/**
* Perform a [indices.clearCache](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-clearcache.html) request
* Perform a [indices.clearCache](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-clearcache.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.fieldData - Clear field data. This is deprecated. Prefer `fielddata`.
@ -2871,7 +2871,7 @@ api.indices.prototype.clearCache = ca({
});
/**
* Perform a [indices.close](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-open-close.html) request
* Perform a [indices.close](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-open-close.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -2922,7 +2922,7 @@ api.indices.prototype.close = ca({
});
/**
* Perform a [indices.create](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-create-index.html) request
* Perform a [indices.create](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-create-index.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether a type should be expected in the body of the mappings.
@ -2966,7 +2966,7 @@ api.indices.prototype.create = ca({
});
/**
* Perform a [indices.delete](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-delete-index.html) request
* Perform a [indices.delete](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-delete-index.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -3017,7 +3017,7 @@ api.indices.prototype['delete'] = ca({
});
/**
* Perform a [indices.deleteAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-aliases.html) request
* Perform a [indices.deleteAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit timestamp for the document
@ -3050,7 +3050,7 @@ api.indices.prototype.deleteAlias = ca({
});
/**
* Perform a [indices.deleteTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-templates.html) request
* Perform a [indices.deleteTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-templates.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -3079,7 +3079,7 @@ api.indices.prototype.deleteTemplate = ca({
});
/**
* Perform a [indices.exists](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-exists.html) request
* Perform a [indices.exists](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-exists.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.local - Return local information, do not retrieve the state from master node (default: false)
@ -3136,7 +3136,7 @@ api.indices.prototype.exists = ca({
});
/**
* Perform a [indices.existsAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-aliases.html) request
* Perform a [indices.existsAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -3196,7 +3196,7 @@ api.indices.prototype.existsAlias = ca({
});
/**
* Perform a [indices.existsTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-templates.html) request
* Perform a [indices.existsTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-templates.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.flatSettings - Return settings in flat format (default: false)
@ -3230,7 +3230,7 @@ api.indices.prototype.existsTemplate = ca({
});
/**
* Perform a [indices.existsType](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-types-exists.html) request
* Perform a [indices.existsType](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-types-exists.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -3280,7 +3280,7 @@ api.indices.prototype.existsType = ca({
});
/**
* Perform a [indices.flush](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-flush.html) request
* Perform a [indices.flush](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-flush.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal)
@ -3336,7 +3336,7 @@ api.indices.prototype.flush = ca({
});
/**
* Perform a [indices.flushSynced](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-synced-flush.html) request
* Perform a [indices.flushSynced](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-synced-flush.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -3383,7 +3383,7 @@ api.indices.prototype.flushSynced = ca({
});
/**
* Perform a [indices.forcemerge](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-forcemerge.html) request
* Perform a [indices.forcemerge](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-forcemerge.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.flush - Specify whether the index should be flushed after performing the operation (default: true)
@ -3444,7 +3444,7 @@ api.indices.prototype.forcemerge = ca({
});
/**
* Perform a [indices.get](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-get-index.html) request
* Perform a [indices.get](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-get-index.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether to add the type name to the response (default: true)
@ -3510,7 +3510,7 @@ api.indices.prototype.get = ca({
});
/**
* Perform a [indices.getAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-aliases.html) request
* Perform a [indices.getAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -3580,7 +3580,7 @@ api.indices.prototype.getAlias = ca({
});
/**
* Perform a [indices.getFieldMapping](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-get-field-mapping.html) request
* Perform a [indices.getFieldMapping](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-get-field-mapping.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether a type should be returned in the body of the mappings.
@ -3675,7 +3675,7 @@ api.indices.prototype.getFieldMapping = ca({
});
/**
* Perform a [indices.getMapping](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-get-mapping.html) request
* Perform a [indices.getMapping](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-get-mapping.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether to add the type name to the response.
@ -3755,7 +3755,7 @@ api.indices.prototype.getMapping = ca({
});
/**
* Perform a [indices.getSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-get-settings.html) request
* Perform a [indices.getSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-get-settings.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Specify timeout for connection to master
@ -3844,7 +3844,7 @@ api.indices.prototype.getSettings = ca({
});
/**
* Perform a [indices.getTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-templates.html) request
* Perform a [indices.getTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-templates.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether a type should be returned in the body of the mappings.
@ -3887,7 +3887,7 @@ api.indices.prototype.getTemplate = ca({
});
/**
* Perform a [indices.getUpgrade](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-upgrade.html) request
* Perform a [indices.getUpgrade](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-upgrade.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -3933,7 +3933,7 @@ api.indices.prototype.getUpgrade = ca({
});
/**
* Perform a [indices.open](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-open-close.html) request
* Perform a [indices.open](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-open-close.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -3989,7 +3989,7 @@ api.indices.prototype.open = ca({
});
/**
* Perform a [indices.putAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-aliases.html) request
* Perform a [indices.putAlias](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit timestamp for the document
@ -4022,7 +4022,7 @@ api.indices.prototype.putAlias = ca({
});
/**
* Perform a [indices.putMapping](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-put-mapping.html) request
* Perform a [indices.putMapping](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-put-mapping.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether a type should be expected in the body of the mappings.
@ -4106,7 +4106,7 @@ api.indices.prototype.putMapping = ca({
});
/**
* Perform a [indices.putSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-update-settings.html) request
* Perform a [indices.putSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-update-settings.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Specify timeout for connection to master
@ -4173,7 +4173,7 @@ api.indices.prototype.putSettings = ca({
});
/**
* Perform a [indices.putTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-templates.html) request
* Perform a [indices.putTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-templates.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether a type should be returned in the body of the mappings.
@ -4222,7 +4222,7 @@ api.indices.prototype.putTemplate = ca({
});
/**
* Perform a [indices.recovery](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-recovery.html) request
* Perform a [indices.recovery](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-recovery.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.detailed - Whether to display detailed information about shard recovery
@ -4257,7 +4257,7 @@ api.indices.prototype.recovery = ca({
});
/**
* Perform a [indices.refresh](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-refresh.html) request
* Perform a [indices.refresh](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-refresh.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -4304,7 +4304,7 @@ api.indices.prototype.refresh = ca({
});
/**
* Perform a [indices.rollover](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-rollover-index.html) request
* Perform a [indices.rollover](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-rollover-index.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.includeTypeName - Whether a type should be included in the body of the mappings.
@ -4362,7 +4362,7 @@ api.indices.prototype.rollover = ca({
});
/**
* Perform a [indices.segments](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-segments.html) request
* Perform a [indices.segments](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-segments.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -4413,7 +4413,7 @@ api.indices.prototype.segments = ca({
});
/**
* Perform a [indices.shardStores](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-shards-stores.html) request
* Perform a [indices.shardStores](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-shards-stores.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.status - A comma-separated list of statuses used to filter on shards to get store information for
@ -4469,7 +4469,7 @@ api.indices.prototype.shardStores = ca({
});
/**
* Perform a [indices.shrink](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-shrink-index.html) request
* Perform a [indices.shrink](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-shrink-index.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.copySettings - whether or not to copy settings from the source index (defaults to false)
@ -4512,7 +4512,7 @@ api.indices.prototype.shrink = ca({
});
/**
* Perform a [indices.split](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-split-index.html) request
* Perform a [indices.split](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-split-index.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.copySettings - whether or not to copy settings from the source index (defaults to false)
@ -4555,7 +4555,7 @@ api.indices.prototype.split = ca({
});
/**
* Perform a [indices.stats](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-stats.html) request
* Perform a [indices.stats](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-stats.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)
@ -4673,7 +4673,7 @@ api.indices.prototype.stats = ca({
});
/**
* Perform a [indices.updateAliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-aliases.html) request
* Perform a [indices.updateAliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Request timeout
@ -4697,7 +4697,7 @@ api.indices.prototype.updateAliases = ca({
});
/**
* Perform a [indices.upgrade](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/indices-upgrade.html) request
* Perform a [indices.upgrade](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-upgrade.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
@ -4754,7 +4754,7 @@ api.indices.prototype.upgrade = ca({
});
/**
* Perform a [indices.validateQuery](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-validate.html) request
* Perform a [indices.validateQuery](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-validate.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.explain - Return detailed information about the error
@ -4870,7 +4870,7 @@ api.info = ca({
api.ingest = namespace();
/**
* Perform a [ingest.deletePipeline](https://www.elastic.co/guide/en/elasticsearch/plugins/6.7/ingest.html) request
* Perform a [ingest.deletePipeline](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/delete-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -4899,7 +4899,7 @@ api.ingest.prototype.deletePipeline = ca({
});
/**
* Perform a [ingest.getPipeline](https://www.elastic.co/guide/en/elasticsearch/plugins/6.7/ingest.html) request
* Perform a [ingest.getPipeline](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/get-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -4928,7 +4928,7 @@ api.ingest.prototype.getPipeline = ca({
});
/**
* Perform a [ingest.processorGrok](https://www.elastic.co/guide/en/elasticsearch/plugins/6.7/ingest.html) request
* Perform a [ingest.processorGrok](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/grok-processor.html#grok-processor-rest-get) request
*
* @param {Object} params - An object with parameters used to carry out this action
*/
@ -4939,7 +4939,7 @@ api.ingest.prototype.processorGrok = ca({
});
/**
* Perform a [ingest.putPipeline](https://www.elastic.co/guide/en/elasticsearch/plugins/6.7/ingest.html) request
* Perform a [ingest.putPipeline](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/put-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -4969,7 +4969,7 @@ api.ingest.prototype.putPipeline = ca({
});
/**
* Perform a [ingest.simulate](https://www.elastic.co/guide/en/elasticsearch/plugins/6.7/ingest.html) request
* Perform a [ingest.simulate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/simulate-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.verbose - Verbose mode. Display data output for each processor in executed pipeline
@ -5000,7 +5000,7 @@ api.ingest.prototype.simulate = ca({
});
/**
* Perform a [mget](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-multi-get.html) request
* Perform a [mget](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-multi-get.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.storedFields - A comma-separated list of stored fields to return in the response
@ -5073,7 +5073,7 @@ api.mget = ca({
});
/**
* Perform a [msearch](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-multi-search.html) request
* Perform a [msearch](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-multi-search.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.searchType - Search operation type
@ -5151,7 +5151,7 @@ api.msearch = ca({
});
/**
* Perform a [msearchTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-multi-search.html) request
* Perform a [msearchTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-multi-search.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.searchType - Search operation type
@ -5217,7 +5217,7 @@ api.msearchTemplate = ca({
});
/**
* Perform a [mtermvectors](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-multi-termvectors.html) request
* Perform a [mtermvectors](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-multi-termvectors.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.ids - A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body
@ -5333,7 +5333,7 @@ api.mtermvectors = ca({
api.nodes = namespace();
/**
* Perform a [nodes.hotThreads](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-nodes-hot-threads.html) request
* Perform a [nodes.hotThreads](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-nodes-hot-threads.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.interval - The interval for the second sampling of threads
@ -5387,7 +5387,7 @@ api.nodes.prototype.hotThreads = ca({
});
/**
* Perform a [nodes.info](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-nodes-info.html) request
* Perform a [nodes.info](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-nodes-info.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.flatSettings - Return settings in flat format (default: false)
@ -5462,7 +5462,7 @@ api.nodes.prototype.info = ca({
});
/**
* Perform a [nodes.reloadSecureSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/secure-settings.html#reloadable-secure-settings) request
* Perform a [nodes.reloadSecureSettings](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/secure-settings.html#reloadable-secure-settings) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -5491,7 +5491,7 @@ api.nodes.prototype.reloadSecureSettings = ca({
});
/**
* Perform a [nodes.stats](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-nodes-stats.html) request
* Perform a [nodes.stats](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-nodes-stats.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)
@ -5691,7 +5691,7 @@ api.nodes.prototype.stats = ca({
});
/**
* Perform a [nodes.usage](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/cluster-nodes-usage.html) request
* Perform a [nodes.usage](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/cluster-nodes-usage.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -5759,7 +5759,7 @@ api.ping = ca({
});
/**
* Perform a [putScript](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-scripting.html) request
* Perform a [putScript](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-scripting.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.timeout - Explicit operation timeout
@ -5806,7 +5806,7 @@ api.putScript = ca({
});
/**
* Perform a [rankEval](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-rank-eval.html) request
* Perform a [rankEval](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-rank-eval.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -5854,7 +5854,7 @@ api.rankEval = ca({
});
/**
* Perform a [reindex](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-reindex.html) request
* Perform a [reindex](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-reindex.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.refresh - Should the effected indexes be refreshed?
@ -5900,7 +5900,7 @@ api.reindex = ca({
});
/**
* Perform a [reindexRethrottle](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-reindex.html) request
* Perform a [reindexRethrottle](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-reindex.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-number,`Number`>>} params.requestsPerSecond - The throttle to set on this request in floating sub-requests per second. -1 means set no throttle.
@ -5926,7 +5926,7 @@ api.reindexRethrottle = ca({
});
/**
* Perform a [renderSearchTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-template.html) request
* Perform a [renderSearchTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-template.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.id - The id of the stored search template
@ -5949,7 +5949,7 @@ api.renderSearchTemplate = ca({
});
/**
* Perform a [scriptsPainlessExecute](https://www.elastic.co/guide/en/elasticsearch/painless/6.7/painless-execute-api.html) request
* Perform a [scriptsPainlessExecute](https://www.elastic.co/guide/en/elasticsearch/painless/6.8/painless-execute-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
*/
@ -5961,7 +5961,7 @@ api.scriptsPainlessExecute = ca({
});
/**
* Perform a [scroll](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-request-scroll.html) request
* Perform a [scroll](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-scroll.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search
@ -6004,7 +6004,7 @@ api.scroll = ca({
});
/**
* Perform a [search](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-search.html) request
* Perform a [search](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-search.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.analyzer - The analyzer to use for the query string
@ -6258,7 +6258,7 @@ api.search = ca({
});
/**
* Perform a [searchShards](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-shards.html) request
* Perform a [searchShards](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-shards.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.preference - Specify the node or shard the operation should be performed on (default: random)
@ -6317,7 +6317,7 @@ api.searchShards = ca({
});
/**
* Perform a [searchTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-template.html) request
* Perform a [searchTemplate](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-template.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
@ -6426,7 +6426,7 @@ api.searchTemplate = ca({
api.snapshot = namespace();
/**
* Perform a [snapshot.create](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.create](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6461,7 +6461,7 @@ api.snapshot.prototype.create = ca({
});
/**
* Perform a [snapshot.createRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.createRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6495,7 +6495,7 @@ api.snapshot.prototype.createRepository = ca({
});
/**
* Perform a [snapshot.delete](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.delete](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6524,7 +6524,7 @@ api.snapshot.prototype['delete'] = ca({
});
/**
* Perform a [snapshot.deleteRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.deleteRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6553,7 +6553,7 @@ api.snapshot.prototype.deleteRepository = ca({
});
/**
* Perform a [snapshot.get](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.get](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6590,7 +6590,7 @@ api.snapshot.prototype.get = ca({
});
/**
* Perform a [snapshot.getRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.getRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6623,7 +6623,7 @@ api.snapshot.prototype.getRepository = ca({
});
/**
* Perform a [snapshot.restore](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.restore](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6658,7 +6658,7 @@ api.snapshot.prototype.restore = ca({
});
/**
* Perform a [snapshot.status](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.status](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6704,7 +6704,7 @@ api.snapshot.prototype.status = ca({
});
/**
* Perform a [snapshot.verifyRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-snapshots.html) request
* Perform a [snapshot.verifyRepository](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/modules-snapshots.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -6735,7 +6735,7 @@ api.snapshot.prototype.verifyRepository = ca({
api.tasks = namespace();
/**
* Perform a [tasks.cancel](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/tasks.html) request
* Perform a [tasks.cancel](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/tasks.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.nodes - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
@ -6773,7 +6773,7 @@ api.tasks.prototype.cancel = ca({
});
/**
* Perform a [tasks.get](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/tasks.html) request
* Perform a [tasks.get](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/tasks.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.waitForCompletion - Wait for the matching tasks to complete (default: false)
@ -6801,7 +6801,7 @@ api.tasks.prototype.get = ca({
});
/**
* Perform a [tasks.list](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/tasks.html) request
* Perform a [tasks.list](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/tasks.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.nodes - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
@ -6851,7 +6851,7 @@ api.tasks.prototype.list = ca({
});
/**
* Perform a [termvectors](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-termvectors.html) request
* Perform a [termvectors](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-termvectors.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.termStatistics - Specifies if total term frequency and document frequency should be returned.
@ -6964,7 +6964,7 @@ api.termvectors = ca({
});
/**
* Perform a [update](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-update.html) request
* Perform a [update](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-update.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.waitForActiveShards - Sets the number of shard copies that must be active before proceeding with the update operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
@ -7070,7 +7070,7 @@ api.update = ca({
});
/**
* Perform a [updateByQuery](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-update-by-query.html) request
* Perform a [updateByQuery](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-update-by-query.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-string,`String`>>} params.analyzer - The analyzer to use for the query string
@ -7281,7 +7281,7 @@ api.updateByQuery = ca({
});
/**
* Perform a [updateByQueryRethrottle](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-update-by-query.html) request
* Perform a [updateByQueryRethrottle](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-update-by-query.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-number,`Number`>>} params.requestsPerSecond - The throttle to set on this request in floating sub-requests per second. -1 means set no throttle.

View File

@ -2539,8 +2539,6 @@ api.fieldCaps = ca({
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params._source - True or false to return the _source field or not, or a list of fields to return
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params._sourceExcludes - A list of fields to exclude from the returned _source field
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params._sourceIncludes - A list of fields to extract and return from the _source field
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params._sourceExclude - A list of fields to exclude from the returned _source field
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params._sourceInclude - A list of fields to extract and return from the _source field
* @param {<<api-param-type-number,`Number`>>} params.version - Explicit version number for concurrency control
* @param {<<api-param-type-string,`String`>>} params.versionType - Specific version type
* @param {<<api-param-type-string,`String`>>} params.id - The document ID
@ -2579,14 +2577,6 @@ api.get = ca({
type: 'list',
name: '_source_includes'
},
_sourceExclude: {
type: 'list',
name: '_source_exclude'
},
_sourceInclude: {
type: 'list',
name: '_source_include'
},
version: {
type: 'number'
},
@ -4956,7 +4946,7 @@ api.info = ca({
api.ingest = namespace();
/**
* Perform a [ingest.deletePipeline](https://www.elastic.co/guide/en/elasticsearch/plugins/7.0/ingest.html) request
* Perform a [ingest.deletePipeline](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/delete-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -4985,7 +4975,7 @@ api.ingest.prototype.deletePipeline = ca({
});
/**
* Perform a [ingest.getPipeline](https://www.elastic.co/guide/en/elasticsearch/plugins/7.0/ingest.html) request
* Perform a [ingest.getPipeline](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/get-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -5014,7 +5004,7 @@ api.ingest.prototype.getPipeline = ca({
});
/**
* Perform a [ingest.processorGrok](https://www.elastic.co/guide/en/elasticsearch/plugins/7.0/ingest.html) request
* Perform a [ingest.processorGrok](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/grok-processor.html#grok-processor-rest-get) request
*
* @param {Object} params - An object with parameters used to carry out this action
*/
@ -5025,7 +5015,7 @@ api.ingest.prototype.processorGrok = ca({
});
/**
* Perform a [ingest.putPipeline](https://www.elastic.co/guide/en/elasticsearch/plugins/7.0/ingest.html) request
* Perform a [ingest.putPipeline](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/put-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-duration-string,`DurationString`>>} params.masterTimeout - Explicit operation timeout for connection to master node
@ -5055,7 +5045,7 @@ api.ingest.prototype.putPipeline = ca({
});
/**
* Perform a [ingest.simulate](https://www.elastic.co/guide/en/elasticsearch/plugins/7.0/ingest.html) request
* Perform a [ingest.simulate](https://www.elastic.co/guide/en/elasticsearch/reference/7.0/simulate-pipeline-api.html) request
*
* @param {Object} params - An object with parameters used to carry out this action
* @param {<<api-param-type-boolean,`Boolean`>>} params.verbose - Verbose mode. Display data output for each processor in executed pipeline
@ -5166,7 +5156,7 @@ api.mget = ca({
* @param {<<api-param-type-number,`Number`>>} params.maxConcurrentSearches - Controls the maximum number of concurrent searches the multi search api will execute
* @param {<<api-param-type-boolean,`Boolean`>>} params.typedKeys - Specify whether aggregation and suggester names should be prefixed by their respective types in the response
* @param {<<api-param-type-number,`Number`>>} [params.preFilterShardSize=128] - A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.
* @param {<<api-param-type-number,`Number`>>} [params.maxConcurrentShardRequests=The default grows with the number of nodes in the cluster but is at most 256.] - The number of concurrent shard requests each sub search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
* @param {<<api-param-type-number,`Number`>>} [params.maxConcurrentShardRequests=5] - The number of concurrent shard requests each sub search executes concurrently per node. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
* @param {<<api-param-type-boolean,`Boolean`>>} params.restTotalHitsAsInt - Indicates whether hits.total should be rendered as an integer or an object in the rest search response
* @param {<<api-param-type-boolean,`Boolean`>>} [params.ccsMinimizeRoundtrips=true] - Indicates whether network round-trips should be minimized as part of cross-cluster search requests execution
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.index - A comma-separated list of index names to use as default
@ -5199,7 +5189,7 @@ api.msearch = ca({
},
maxConcurrentShardRequests: {
type: 'number',
'default': 'The default grows with the number of nodes in the cluster but is at most 256.',
'default': 5,
name: 'max_concurrent_shard_requests'
},
restTotalHitsAsInt: {
@ -5960,6 +5950,7 @@ api.rankEval = ca({
* @param {<<api-param-type-string,`String`>>} params.waitForActiveShards - Sets the number of shard copies that must be active before proceeding with the reindex operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
* @param {<<api-param-type-boolean,`Boolean`>>} [params.waitForCompletion=true] - Should the request should block until the reindex is complete.
* @param {<<api-param-type-number,`Number`>>} params.requestsPerSecond - The throttle to set on this request in sub-requests per second. -1 means no throttle.
* @param {<<api-param-type-duration-string,`DurationString`>>} [params.scroll=5m] - Control how long to keep the search context alive
* @param {<<api-param-type-number,`Number`>>} [params.slices=1] - The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks.
*/
api.reindex = ca({
@ -5985,6 +5976,10 @@ api.reindex = ca({
'default': 0,
name: 'requests_per_second'
},
scroll: {
type: 'time',
'default': '5m'
},
slices: {
type: 'number',
'default': 1
@ -6144,7 +6139,7 @@ api.scroll = ca({
* @param {<<api-param-type-boolean,`Boolean`>>} params.seqNoPrimaryTerm - Specify whether to return sequence number and primary term of the last modification of each hit
* @param {<<api-param-type-boolean,`Boolean`>>} params.requestCache - Specify if request cache should be used for this request or not, defaults to index level setting
* @param {<<api-param-type-number,`Number`>>} [params.batchedReduceSize=512] - The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large.
* @param {<<api-param-type-number,`Number`>>} [params.maxConcurrentShardRequests=The default is 5.] - The number of concurrent shard requests per node this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
* @param {<<api-param-type-number,`Number`>>} [params.maxConcurrentShardRequests=5] - The number of concurrent shard requests per node this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests
* @param {<<api-param-type-number,`Number`>>} [params.preFilterShardSize=128] - A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.
* @param {<<api-param-type-boolean,`Boolean`>>} params.restTotalHitsAsInt - Indicates whether hits.total should be rendered as an integer or an object in the rest search response
* @param {<<api-param-type-string,`String`>>, <<api-param-type-string-array,`String[]`>>, <<api-param-type-boolean,`Boolean`>>} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
@ -6320,7 +6315,7 @@ api.search = ca({
},
maxConcurrentShardRequests: {
type: 'number',
'default': 'The default is 5.',
'default': 5,
name: 'max_concurrent_shard_requests'
},
preFilterShardSize: {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

7158
src/lib/apis/7_3.js Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

7098
src/lib/apis/7_5.js Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,11 @@
module.exports = {
'_default': require('./6_6'),
'6.6': require('./6_6'),
'6.5': require('./6_5'),
'6.4': require('./6_4'),
'6.3': require('./6_3'),
'6.2': require('./6_2'),
'6.7': require('./6_7'),
'_default': require('./7_4'),
'7.4': require('./7_4'),
'7.3': require('./7_3'),
'7.2': require('./7_2'),
'7.1': require('./7_1'),
'7.0': require('./7_0'),
'7.5': require('./7_5'),
'7.x': require('./7_x'),
'master': require('./master')
};

View File

@ -1,18 +1,13 @@
module.exports = {
get '_default'() { return require('./6_6'); },
get '6.6'() { return require('./6_6'); },
get '6.5'() { return require('./6_5'); },
get '6.4'() { return require('./6_4'); },
get '6.3'() { return require('./6_3'); },
get '6.2'() { return require('./6_2'); },
get '6.1'() { return require('./6_1'); },
get '6.0'() { return require('./6_0'); },
get '5.6'() { return require('./5_6'); },
get '2.4'() { return require('./2_4'); },
get '1.7'() { return require('./1_7'); },
get '0.90'() { return require('./0_90'); },
get '6.7'() { return require('./6_7'); },
get '_default'() { return require('./7_4'); },
get '7.4'() { return require('./7_4'); },
get '7.3'() { return require('./7_3'); },
get '7.2'() { return require('./7_2'); },
get '7.1'() { return require('./7_1'); },
get '7.0'() { return require('./7_0'); },
get '6.8'() { return require('./6_8'); },
get '5.6'() { return require('./5_6'); },
get '7.5'() { return require('./7_5'); },
get '7.x'() { return require('./7_x'); },
get 'master'() { return require('./master'); },
};

File diff suppressed because it is too large Load Diff

View File

@ -35,8 +35,10 @@ function Client(config) {
config = config || {};
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 {
config.__reused = true;
}
@ -51,23 +53,30 @@ function Client(config) {
config.host = 'http://localhost:9200';
}
this.close = function () {
this.close = function() {
this.transport.close();
};
this.transport = new Transport(config);
_.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)
);
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']) {
config.sniffEndpoint = '/_cluster/nodes';
}
@ -77,24 +86,25 @@ function Client(config) {
if (config.plugins) {
Constructor.prototype = _.cloneDeep(Constructor.prototype);
_.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;
});
}

View File

@ -1,4 +1,3 @@
var _ = require('lodash');
var utils = require('./utils');
@ -23,8 +22,8 @@ exports.proxyFactory = exports.factory.proxy;
// export so that we can test this
exports._resolveUrl = resolveUrl;
exports.ApiNamespace = function () {};
exports.namespaceFactory = function () {
exports.ApiNamespace = function() {};
exports.namespaceFactory = function() {
function ClientNamespace(transport, client) {
this.transport = transport;
this.client = client;
@ -38,7 +37,7 @@ exports.namespaceFactory = function () {
function makeFactoryWithModifier(modifier) {
modifier = modifier || _.identity;
var factory = function (spec) {
var factory = function(spec) {
spec = modifier(spec);
if (!_.isPlainObject(spec.params)) {
@ -76,8 +75,8 @@ function makeFactoryWithModifier(modifier) {
return action;
};
factory.proxy = function (fn, spec) {
return function (params, cb) {
factory.proxy = function(fn, spec) {
return function(params, cb) {
if (typeof params === 'function') {
cb = params;
params = {};
@ -98,15 +97,17 @@ function makeFactoryWithModifier(modifier) {
}
var castType = {
'enum': function validSelection(param, val, name) {
enum: function validSelection(param, val, name) {
if (_.isString(val) && val.indexOf(',') > -1) {
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(',');
}
for (var i = 0; i < param.options.length; i++) {
@ -114,23 +115,28 @@ var castType = {
return param.options[i];
}
}
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)) {
return val;
} else {
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) {
case 'number':
case 'boolean':
@ -144,21 +150,25 @@ var castType = {
}
/* falls through */
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)) {
return val * 1;
} else {
throw new TypeError('Invalid ' + name + ': expected a number.');
}
},
string: function (param, val, name) {
string: function(param, val, name) {
switch (typeof val) {
case 'number':
case 'string':
@ -167,24 +177,23 @@ var castType = {
throw new TypeError('Invalid ' + name + ': expected a string.');
}
},
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;
if (url.req) {
// url has required params
@ -193,7 +202,7 @@ function resolveUrl(url, params) {
url.reqParamKeys = _.keys(url.req);
}
for (i = 0; i < url.reqParamKeys.length; i ++) {
for (i = 0; i < url.reqParamKeys.length; i++) {
key = url.reqParamKeys[i];
if (!params.hasOwnProperty(key) || params[key] == null) {
// missing a required param
@ -201,7 +210,11 @@ function resolveUrl(url, params) {
} else {
// cast of copy required param
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 {
vars[key] = params[key];
}
@ -215,11 +228,15 @@ function resolveUrl(url, params) {
url.optParamKeys = _.keys(url.opt);
}
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 {
vars[key] = params[key];
}
@ -234,18 +251,23 @@ function resolveUrl(url, params) {
url.template = _.template(url.fmt);
}
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,
};
var query = {};
var i;
@ -259,7 +281,9 @@ function exec(transport, spec, params, cb) {
if (typeof spec.paramAsBody === 'object') {
params.body = {};
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 {
params.body[spec.paramAsBody.body] = params[spec.paramAsBody.param];
}
@ -290,7 +314,8 @@ function exec(transport, spec, params, cb) {
request.path = resolveUrl(spec.url, params);
} else {
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;
}
}
@ -299,18 +324,25 @@ function exec(transport, spec, params, cb) {
if (!request.path) {
// there must have been some mimimun requirements that were not met
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(', ')
);
}
// build the query string
if (!spec.paramKeys) {
// build a key list on demand
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);
}
},
[]
);
}
for (var key in params) {
@ -331,16 +363,23 @@ function exec(transport, spec, params, cb) {
default:
var paramSpec = spec.params[key];
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 {
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];
}
}
@ -351,9 +390,11 @@ function exec(transport, spec, params, cb) {
}
}
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]
);
}
}
@ -363,7 +404,7 @@ function exec(transport, spec, params, cb) {
}
function commaSepList(str) {
return str.split(',').map(function (i) {
return str.split(',').map(function(i) {
return i.trim();
});
}

View File

@ -41,11 +41,11 @@ utils.inherits(ConnectionAbstract, EventEmitter);
* @param params.requestTimeout {Integer} - The amount of time in milliseconds that this request should be allowed to run for.
* @param cb {Function} - A callback to be called once with `cb(err, responseBody, responseStatus)`
*/
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') {
cb = params;
params = null;
@ -62,33 +62,40 @@ ConnectionAbstract.prototype.ping = function (params, cb) {
requestTimeout = params.requestTimeout;
}
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) {
abort();
}
aborted = true;
if (cb) {
cb(new errors.RequestTimeout('Ping Timeout after ' + requestTimeout + 'ms'));
cb(
new errors.RequestTimeout(
'Ping Timeout after ' + requestTimeout + 'ms'
)
);
}
}, requestTimeout);
}
};
ConnectionAbstract.prototype.setStatus = function (status) {
ConnectionAbstract.prototype.setStatus = function(status) {
var origStatus = this.status;
this.status = status;

View File

@ -28,23 +28,41 @@ function ConnectionPool(config) {
this._config = config;
// 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'
);
// a map of connections to their "id" property, used when sniffing
this.index = {};
this._conns = {
alive: [],
dead: []
dead: [],
};
// information about timeouts for dead connections
@ -57,17 +75,21 @@ ConnectionPool.defaultSelector = 'roundRobin';
// get the connection options
ConnectionPool.connectionClasses = require('./connectors');
ConnectionPool.defaultConnectionClass = ConnectionPool.connectionClasses._default;
ConnectionPool.defaultConnectionClass =
ConnectionPool.connectionClasses._default;
delete ConnectionPool.connectionClasses._default;
// the function that calculates timeouts based on attempts
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
);
},
};
/**
@ -81,7 +103,7 @@ ConnectionPool.calcDeadTimeoutOptions = {
* @param {Function} cb [description]
* @return {[type]} [description]
*/
ConnectionPool.prototype.select = function (cb) {
ConnectionPool.prototype.select = function(cb) {
if (this._conns.alive.length) {
if (this.selector.length > 1) {
this.selector(this._conns.alive, cb);
@ -107,13 +129,17 @@ ConnectionPool.prototype.select = function (cb) {
* @param {String} oldStatus - the connection's old status
* @param {ConnectionAbstract} connection - the connection object itself
*/
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];
var to = this._conns[status];
@ -150,7 +176,7 @@ ConnectionPool.prototype.onStatusSet = utils.handler(function (status, oldStatus
* Handler used to clear the times created when a connection dies
* @param {ConnectionAbstract} connection
*/
ConnectionPool.prototype._onConnectionRevived = function (connection) {
ConnectionPool.prototype._onConnectionRevived = function(connection) {
var timeout;
for (var i = 0; i < this._timeouts.length; i++) {
if (this._timeouts[i].conn === connection) {
@ -169,7 +195,10 @@ ConnectionPool.prototype._onConnectionRevived = function (connection) {
* @param {ConnectionAbstract} connection
* @param {Boolean} alreadyWasDead - If the connection was preivously dead this must be set to true
*/
ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDead) {
ConnectionPool.prototype._onConnectionDied = function(
connection,
alreadyWasDead
) {
var timeout;
if (alreadyWasDead) {
for (var i = 0; i < this._timeouts.length; i++) {
@ -182,15 +211,15 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea
timeout = {
conn: connection,
attempt: 0,
revive: function (cb) {
revive: function(cb) {
timeout.attempt++;
connection.ping(function (err) {
connection.ping(function(err) {
connection.setStatus(err ? 'dead' : 'alive');
if (cb && typeof cb === 'function') {
cb(err);
}
});
}
},
};
this._timeouts.push(timeout);
}
@ -204,7 +233,7 @@ ConnectionPool.prototype._onConnectionDied = function (connection, alreadyWasDea
timeout.runAt = utils.now() + ms;
};
ConnectionPool.prototype._selectDeadConnection = function (cb) {
ConnectionPool.prototype._selectDeadConnection = function(cb) {
var orderedTimeouts = _.sortBy(this._timeouts, 'runAt');
var log = this.log;
@ -221,7 +250,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) {
}
if (timeout.conn.status === 'dead') {
timeout.revive(function (err) {
timeout.revive(function(err) {
if (err) {
log.warning('Unable to revive connection: ' + timeout.conn.id);
process.nextTick(next);
@ -247,7 +276,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) {
* @param {string} [status] - optional status of the connection to fetch
* @param {Number} [limit] - optional limit on the number of connections to return
*/
ConnectionPool.prototype.getConnections = function (status, limit) {
ConnectionPool.prototype.getConnections = function(status, limit) {
var list;
if (status) {
list = this._conns[status];
@ -268,7 +297,7 @@ ConnectionPool.prototype.getConnections = function (status, limit) {
*
* @param {ConnectionAbstract} connection - The connection to add
*/
ConnectionPool.prototype.addConnection = function (connection) {
ConnectionPool.prototype.addConnection = function(connection) {
if (!connection.id) {
connection.id = connection.host.toString();
}
@ -286,7 +315,7 @@ ConnectionPool.prototype.addConnection = function (connection) {
*
* @param {ConnectionAbstract} connection - The connection to remove/close
*/
ConnectionPool.prototype.removeConnection = function (connection) {
ConnectionPool.prototype.removeConnection = function(connection) {
if (!connection.id) {
connection.id = connection.host.toString();
}
@ -304,7 +333,7 @@ ConnectionPool.prototype.removeConnection = function (connection) {
*
* @param {Host[]} hosts - An array of Host instances.
*/
ConnectionPool.prototype.setHosts = function (hosts) {
ConnectionPool.prototype.setHosts = function(hosts) {
var connection;
var i;
var id;
@ -329,8 +358,8 @@ ConnectionPool.prototype.setHosts = function (hosts) {
}
};
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;
});
};
@ -338,7 +367,7 @@ ConnectionPool.prototype.getAllHosts = function () {
/**
* Close the conncetion pool, as well as all of it's connections
*/
ConnectionPool.prototype.close = function () {
ConnectionPool.prototype.close = function() {
this.setHosts([]);
};
ConnectionPool.prototype.empty = ConnectionPool.prototype.close;

View File

@ -14,15 +14,18 @@ function AngularConnector(host, config) {
ConnectionAbstract.call(this, host, config);
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();
this.$http({
@ -34,18 +37,21 @@ AngularConnector.prototype.request = function (params, cb) {
transformRequest: [],
transformResponse: [],
// 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();
};
};

View File

@ -1,12 +1,12 @@
var opts = {
xhr: require('./xhr'),
jquery: require('./jquery'),
angular: require('./angular')
angular: require('./angular'),
};
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') {
delete opts[name];
}

View File

@ -10,7 +10,7 @@ module.exports = HttpConnector;
var handles = {
http: require('http'),
https: require('https')
https: require('https'),
};
var _ = require('lodash');
var utils = require('../utils');
@ -19,7 +19,7 @@ var qs = require('querystring');
var AgentKeepAlive = require('agentkeepalive');
var ConnectionAbstract = require('../connection');
var zlib = require('zlib');
var INVALID_PATH_REGEX = /[^\u0021-\u00ff]/
var INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
/**
* Connector used to talk to an elasticsearch node via HTTP
@ -33,8 +33,12 @@ function HttpConnector(host, config) {
this.hand = handles[this.host.protocol];
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(', ')
);
}
this.useSsl = this.host.protocol === 'https';
@ -44,19 +48,21 @@ function HttpConnector(host, config) {
keepAlive: true,
keepAliveInterval: 1000,
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]);
});
};
@ -66,15 +72,16 @@ HttpConnector.prototype.onStatusSet = utils.handler(function (status) {
_.each(agent.sockets, collectSockets);
_.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));
socket.destroy();
});
}
});
HttpConnector.prototype.createAgent = function (config) {
HttpConnector.prototype.createAgent = function(config) {
var Agent = this.hand.Agent; // the class
if (config.forever) {
@ -89,7 +96,7 @@ HttpConnector.prototype.createAgent = function (config) {
return new Agent(this.makeAgentConfig(config));
};
HttpConnector.prototype.makeAgentConfig = function (config) {
HttpConnector.prototype.makeAgentConfig = function(config) {
var agentConfig = {
keepAlive: config.keepAlive,
keepAliveMsecs: config.keepAliveInterval,
@ -105,7 +112,7 @@ HttpConnector.prototype.makeAgentConfig = function (config) {
return agentConfig;
};
HttpConnector.prototype.makeReqParams = function (params) {
HttpConnector.prototype.makeReqParams = function(params) {
params = params || {};
var host = this.host;
@ -116,7 +123,7 @@ HttpConnector.prototype.makeReqParams = function (params) {
port: host.port,
path: (host.path || '') + (params.path || ''),
headers: host.getHeaders(params.headers),
agent: this.agent
agent: this.agent,
};
if (!reqParams.path) {
@ -131,7 +138,7 @@ HttpConnector.prototype.makeReqParams = function (params) {
return reqParams;
};
HttpConnector.prototype.request = function (params, cb) {
HttpConnector.prototype.request = function(params, cb) {
var incoming;
var timeoutId;
var request;
@ -144,7 +151,7 @@ HttpConnector.prototype.request = function (params, cb) {
// general clean-up procedure to run after the request
// completes, has an error, or is aborted.
var cleanUp = _.bind(function (err) {
var cleanUp = _.bind(function(err) {
clearTimeout(timeoutId);
if (request) {
@ -155,7 +162,7 @@ HttpConnector.prototype.request = function (params, cb) {
incoming.removeAllListeners();
}
if ((err instanceof Error) === false) {
if (err instanceof Error === false) {
err = void 0;
}
@ -168,11 +175,11 @@ HttpConnector.prototype.request = function (params, cb) {
}, this);
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;
status = incoming.statusCode;
headers = incoming.headers;
@ -184,7 +191,7 @@ HttpConnector.prototype.request = function (params, cb) {
}
incoming.setEncoding('utf8');
incoming.on('data', function (d) {
incoming.on('data', function(d) {
response += d;
});
@ -205,7 +212,7 @@ HttpConnector.prototype.request = function (params, cb) {
request.end();
}
return function () {
return function() {
request.abort();
};
};

View File

@ -1,4 +1,4 @@
module.exports = {
http: require('./http'),
_default: 'http'
_default: 'http',
};

View File

@ -16,34 +16,35 @@ function JqueryConnector(host, config) {
}
utils.inherits(JqueryConnector, ConnectionAbstract);
JqueryConnector.prototype.request = function (params, cb) {
JqueryConnector.prototype.request = function(params, cb) {
var ajax = {
url: this.host.makeUrl(params),
data: params.body,
type: params.method,
dataType: 'text',
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'),
});
} else {
cb(new ConnectionFault(err && err.message));
}
});
return function () {
return function() {
jqXHR.abort();
};
};

View File

@ -5,8 +5,9 @@
*/
module.exports = XhrConnector;
/* jshint browser:true */
/* eslint-env browser */
var _ = require('lodash');
var utils = require('../utils');
var ConnectionAbstract = require('../connection');
var ConnectionFault = require('../errors').ConnectionFault;
@ -25,32 +26,31 @@ var getXhr = _.noop;
if (typeof XMLHttpRequest !== 'undefined') {
// rewrite the getXhr method to always return the native implementation
getXhr = function () {
getXhr = function() {
return new XMLHttpRequest();
};
} else {
// find the first MS implementation available
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();
}
if (!getXhr) {
throw new Error('getXhr(): XMLHttpRequest not available');
}
XhrConnector.prototype.request = function (params, cb) {
XhrConnector.prototype.request = function(params, cb) {
var xhr = getXhr();
var timeoutId;
var host = this.host;
@ -70,18 +70,20 @@ XhrConnector.prototype.request = function (params, cb) {
}
}
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);
}
};
xhr.send(params.body || void 0);
return function () {
return function() {
xhr.abort();
};
};

View File

@ -2,8 +2,8 @@ var _ = require('lodash');
var utils = require('./utils');
var errors = module.exports;
var canCapture = (typeof Error.captureStackTrace === 'function');
var canStack = !!(new Error()).stack;
var canCapture = typeof Error.captureStackTrace === 'function';
var canStack = !!new Error().stack;
function ErrorAbstract(msg, constructor, metadata) {
this.message = msg;
@ -12,25 +12,26 @@ function ErrorAbstract(msg, constructor, metadata) {
if (canCapture) {
Error.captureStackTrace(this, constructor);
}
else if (canStack) {
this.stack = (new Error()).stack;
}
else {
} else if (canStack) {
this.stack = new Error().stack;
} else {
this.stack = '';
}
if (metadata) {
_.assign(this, metadata);
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
);
};
}
}
@ -51,7 +52,11 @@ utils.inherits(errors.ConnectionFault, ErrorAbstract);
* @param {String} [msg] - An error message that will probably end up in a log.
*/
errors.NoConnections = function NoConnections(msg) {
ErrorAbstract.call(this, msg || 'No Living connections', errors.NoConnections);
ErrorAbstract.call(
this,
msg || 'No Living connections',
errors.NoConnections
);
};
utils.inherits(errors.NoConnections, ErrorAbstract);
@ -73,22 +78,28 @@ errors.RequestTimeout = function RequestTimeout(msg) {
};
utils.inherits(errors.RequestTimeout, ErrorAbstract);
/**
* Request Body could not be parsed
* @param {String} [msg] - An error message that will probably end up in a log.
*/
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);
/**
* 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
);
};
utils.inherits(errors.RequestTypeError, ErrorAbstract);
@ -134,7 +145,7 @@ var statusCodes = [
[504, 'Gateway Timeout'],
[505, 'HTTPVersion Not Supported'],
[506, 'Variant Also Negotiates'],
[510, 'Not Extended']
[510, 'Not Extended'],
];
_.each(statusCodes, function createStatusCodeError(tuple) {
@ -163,7 +174,7 @@ _.each(statusCodes, function createStatusCodeError(tuple) {
return this;
}
msg = [].concat(esErrObject.root_cause || []).reduce(function (memo, cause) {
msg = [].concat(esErrObject.root_cause || []).reduce(function(memo, cause) {
if (memo) memo += ' (and) ';
memo += '[' + cause.type + '] ' + cause.reason;
@ -186,27 +197,30 @@ _.each(statusCodes, function createStatusCodeError(tuple) {
}
utils.inherits(StatusCodeError, ErrorAbstract);
allNames.forEach(function (name) {
allNames.forEach(function(name) {
errors[name] = StatusCodeError;
});
});
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);
}

View File

@ -18,12 +18,19 @@ if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
btoa = window.btoa;
}
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',
];
var simplify = ['host', 'path'];
@ -36,14 +43,14 @@ var sslDefaults = {
ca: null,
ciphers: null,
rejectUnauthorized: false,
secureProtocol: null
secureProtocol: null,
};
// simple reference used when formatting as a url
// and defines when parsing from a string
Host.defaultPorts = {
http: 80,
https: 443
https: 443,
};
function Host(config, globalConfig) {
@ -59,7 +66,12 @@ function Host(config, globalConfig) {
this.headers = null;
this.suggestCompression = !!globalConfig.suggestCompression;
this.ssl = _.defaults({}, config.ssl || {}, globalConfig.ssl || {}, sslDefaults);
this.ssl = _.defaults(
{},
config.ssl || {},
globalConfig.ssl || {},
sslDefaults
);
if (typeof config === 'string') {
var firstColon = config.indexOf(':');
@ -67,7 +79,10 @@ function Host(config, globalConfig) {
var noSlash = firstSlash === -1;
var portNoPath = firstColon > -1 && noSlash;
var portWithPath = !portNoPath && firstColon < firstSlash;
if ((noSlash || portNoPath || portWithPath) && !startsWithProtocolRE.test(config)) {
if (
(noSlash || portNoPath || portWithPath) &&
!startsWithProtocolRE.test(config)
) {
config = defaultProto + '//' + config;
}
config = _.pick(url.parse(config, false, true), urlParseFields);
@ -86,7 +101,7 @@ function Host(config, globalConfig) {
if (_.isObject(config)) {
// move hostname/portname to host/port semi-intelligently.
_.each(simplify, function (to) {
_.each(simplify, function(to) {
var from = to + 'name';
if (config[from] && config[to]) {
if (config[to].indexOf(config[from]) === 0) {
@ -102,7 +117,7 @@ function Host(config, globalConfig) {
}
if (!config.auth && globalConfig.httpAuth) {
config.auth = globalConfig.httpAuth
config.auth = globalConfig.httpAuth;
}
if (config.auth) {
@ -111,9 +126,12 @@ function Host(config, globalConfig) {
delete config.auth;
}
_.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)
);
// make sure the query string is parsed
if (this.query === null) {
@ -143,7 +161,7 @@ function Host(config, globalConfig) {
}
}
Host.prototype.makeUrl = function (params) {
Host.prototype.makeUrl = function(params) {
params = params || {};
// build the port
var port = '';
@ -164,14 +182,21 @@ Host.prototype.makeUrl = function (params) {
var query = qs.stringify(this.getQuery(params.query));
if (this.host) {
return this.protocol + '://' + this.host + port + path + (query ? '?' + query : '');
return (
this.protocol +
'://' +
this.host +
port +
path +
(query ? '?' + query : '')
);
} else {
return path + (query ? '?' + query : '');
}
};
function objectPropertyGetter(prop, preOverride) {
return function (overrides) {
return function(overrides) {
if (preOverride) {
overrides = preOverride.call(this, overrides);
}
@ -189,20 +214,22 @@ function objectPropertyGetter(prop, preOverride) {
};
}
Host.prototype.getHeaders = objectPropertyGetter('headers', function (overrides) {
Host.prototype.getHeaders = objectPropertyGetter('headers', function(
overrides
) {
if (!this.suggestCompression) {
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();
};

View File

@ -26,25 +26,29 @@ function Log(config) {
var outputs;
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)) {
return val;
}
if (typeof val === 'string') {
return {
level: val
level: val,
};
}
});
}
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.'
);
}
for (i = 0; i < outputs.length; i++) {
@ -55,10 +59,12 @@ utils.inherits(Log, EventEmitter);
Log.loggers = require('./loggers');
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();
}
};
@ -67,19 +73,17 @@ if (EventEmitter.prototype.listenerCount) {
// If the event emitter implements it's own listenerCount method
// we don't need to (newer nodes do this).
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;
};
}
@ -135,7 +139,7 @@ Log.levels = [
* @param {Integer} responseStatus - The status code returned from the response
* @param {String} responseBody - The body of the response
*/
'trace'
'trace',
];
/**
@ -149,7 +153,7 @@ Log.levels = [
* level, or an array of exact levels
* @return {Array} -
*/
Log.parseLevels = function (input) {
Log.parseLevels = function(input) {
switch (typeof input) {
case 'string':
var i = _.indexOf(Log.levels, input);
@ -166,8 +170,12 @@ Log.parseLevels = function (input) {
}
/* fall through */
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(', ')
);
}
};
@ -180,8 +188,8 @@ Log.parseLevels = function (input) {
* @param {*} arrayish - An array like object that can be itterated by _.each
* @return {String} - The final string.
*/
Log.join = function (arrayish) {
return _.map(arrayish, function (item) {
Log.join = function(arrayish) {
return _.map(arrayish, function(item) {
if (_.isPlainObject(item)) {
return JSON.stringify(item, null, 2) + '\n';
} else {
@ -203,14 +211,19 @@ Log.join = function (arrayish) {
* levels will be logged.
* @return {Logger}
*/
Log.prototype.addOutput = function (config) {
Log.prototype.addOutput = function(config) {
config = config || {};
// force "levels" key
config.levels = Log.parseLevels(config.levels || config.level || 'warning');
delete config.level;
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);
};
@ -221,13 +234,12 @@ Log.prototype.addOutput = function (config) {
* @param {Error|String} error The Error to log
* @return {Boolean} - True if any outputs accepted the message
*/
Log.prototype.error = function (e) {
Log.prototype.error = function(e) {
if (this.listenerCount('error')) {
return this.emit('error', e instanceof Error ? e : new Error(e));
}
};
/**
* Log a warning message
*
@ -235,13 +247,12 @@ Log.prototype.error = function (e) {
* @param {*} msg* - Any amount of messages that will be joined before logged
* @return {Boolean} - True if any outputs accepted the message
*/
Log.prototype.warning = function (/* ...msg */) {
Log.prototype.warning = function(/* ...msg */) {
if (this.listenerCount('warning')) {
return this.emit('warning', Log.join(arguments));
}
};
/**
* Log useful info about what's going on
*
@ -249,7 +260,7 @@ Log.prototype.warning = function (/* ...msg */) {
* @param {*} msg* - Any amount of messages that will be joined before logged
* @return {Boolean} - True if any outputs accepted the message
*/
Log.prototype.info = function (/* ...msg */) {
Log.prototype.info = function(/* ...msg */) {
if (this.listenerCount('info')) {
return this.emit('info', Log.join(arguments));
}
@ -262,7 +273,7 @@ Log.prototype.info = function (/* ...msg */) {
* @param {*} msg* - Any amount of messages that will be joined before logged
* @return {Boolean} - True if any outputs accepted the message
*/
Log.prototype.debug = function (/* ...msg */) {
Log.prototype.debug = function(/* ...msg */) {
if (this.listenerCount('debug')) {
return this.emit('debug', Log.join(arguments));
}
@ -280,13 +291,34 @@ Log.prototype.debug = function (/* ...msg */) {
* @param {String} responseStatus - HTTP status code
* @return {Boolean} - True if any outputs accepted the message
*/
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') {
requestUrl = url.parse(requestUrl, true, true);
} else {
@ -306,7 +338,7 @@ Log.normalizeTraceArgs = function (method, requestUrl, body, responseBody, respo
url: url.format(requestUrl),
body: body,
status: responseStatus,
response: responseBody
response: responseBody,
};
};

View File

@ -27,28 +27,39 @@ function padNumToTen(n) {
* Also, feel free to override this at the logger level.
* @return {String} - Timestamp in ISO 8601 UTC
*/
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'
);
};
function indent(text, spaces) {
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');
};
@ -60,20 +71,23 @@ LoggerAbstract.prototype.write = function () {
* @param {Integer} level - The max log level that this logger should listen to
* @return {undefined}
*/
LoggerAbstract.prototype.setupListeners = function (levels) {
LoggerAbstract.prototype.setupListeners = function(levels) {
this.cleanUpListeners();
this.listeningLevels = [];
_.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)
);
};
/**
@ -83,10 +97,13 @@ LoggerAbstract.prototype.setupListeners = function (levels) {
* @private
* @return {undefined}
*/
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)
);
});
/**
@ -97,8 +114,8 @@ LoggerAbstract.prototype.cleanUpListeners = utils.handler(function () {
* @param {Error} e - The Error object to log
* @return {undefined}
*/
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);
});
/**
@ -109,7 +126,7 @@ LoggerAbstract.prototype.onError = utils.handler(function (e) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
LoggerAbstract.prototype.onWarning = utils.handler(function (msg) {
LoggerAbstract.prototype.onWarning = utils.handler(function(msg) {
this.write('WARNING', msg);
});
@ -121,7 +138,7 @@ LoggerAbstract.prototype.onWarning = utils.handler(function (msg) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
LoggerAbstract.prototype.onInfo = utils.handler(function (msg) {
LoggerAbstract.prototype.onInfo = utils.handler(function(msg) {
this.write('INFO', msg);
});
@ -133,7 +150,7 @@ LoggerAbstract.prototype.onInfo = utils.handler(function (msg) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
LoggerAbstract.prototype.onDebug = utils.handler(function (msg) {
LoggerAbstract.prototype.onDebug = utils.handler(function(msg) {
this.write('DEBUG', msg);
});
@ -145,16 +162,25 @@ LoggerAbstract.prototype.onDebug = utils.handler(function (msg) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
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
{
asdflksjdf
@ -167,7 +193,7 @@ LoggerAbstract.prototype._formatTraceMessage = function (req) {
*/
};
LoggerAbstract.prototype._prettyJson = function (body) {
LoggerAbstract.prototype._prettyJson = function(body) {
try {
if (typeof body === 'string') {
body = JSON.parse(body);

View File

@ -1,3 +1,3 @@
module.exports = {
console: require('./console')
console: require('./console'),
};

View File

@ -29,12 +29,12 @@ utils.inherits(Console, LoggerAbstract);
*
* @param {Array} levels - The levels that we should be listeneing for
*/
Console.prototype.setupListeners = function (levels) {
Console.prototype.setupListeners = function(levels) {
// call the super method
LoggerAbstract.prototype.setupListeners.call(this, levels);
};
Console.prototype.write = function (label, message, to) {
Console.prototype.write = function(label, message, to) {
if (console[to]) {
console[to](this.format(label, message));
}
@ -48,7 +48,7 @@ Console.prototype.write = function (label, message, to) {
* @param {Error} e - The Error object to log
* @return {undefined}
*/
Console.prototype.onError = utils.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);
});
@ -61,7 +61,7 @@ Console.prototype.onError = utils.handler(function (e) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
Console.prototype.onWarning = utils.handler(function (msg) {
Console.prototype.onWarning = utils.handler(function(msg) {
this.write('WARNING', msg, console.warn ? 'warn' : 'log');
});
@ -73,7 +73,7 @@ Console.prototype.onWarning = utils.handler(function (msg) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
Console.prototype.onInfo = utils.handler(function (msg) {
Console.prototype.onInfo = utils.handler(function(msg) {
this.write('INFO', msg, console.info ? 'info' : 'log');
});
@ -85,7 +85,7 @@ Console.prototype.onInfo = utils.handler(function (msg) {
* @param {String} msg - The message to be logged
* @return {undefined}
*/
Console.prototype.onDebug = utils.handler(function (msg) {
Console.prototype.onDebug = utils.handler(function(msg) {
this.write('DEBUG', msg, console.debug ? 'debug' : 'log');
});
/**
@ -95,6 +95,6 @@ Console.prototype.onDebug = utils.handler(function (msg) {
* @private
* @return {undefined}
*/
Console.prototype.onTrace = utils.handler(function (msg) {
Console.prototype.onTrace = utils.handler(function(msg) {
this.write('TRACE', this._formatTraceMessage(msg), 'log');
});

View File

@ -24,14 +24,14 @@ function File(log, config) {
// yahoo!
config.stream = fs.createWriteStream(this.path, {
flags: 'a',
encoding: 'utf8'
encoding: 'utf8',
});
StreamLogger.call(this, log, config);
}
utils.inherits(File, StreamLogger);
File.prototype.onProcessExit = utils.handler(function () {
File.prototype.onProcessExit = utils.handler(function() {
var toWrite = utils.getUnwrittenFromStream(this.stream);
if (toWrite) {
fs.appendFileSync(this.path, toWrite);

Some files were not shown because too many files have changed in this diff Show More