From edf93df9d8e251709b8019a50533650fbb0777c9 Mon Sep 17 00:00:00 2001 From: spalger Date: Wed, 24 Aug 2016 16:39:11 -0700 Subject: [PATCH 01/33] upgrade eslint, all related deps, and config files --- .eslintignore | 2 + .eslintrc | 6 +++ package.json | 10 ++--- src/core_plugins/console/.eslintrc | 60 +++++++++++++------------ src/core_plugins/timelion/.eslintrc | 68 ----------------------------- 5 files changed, 44 insertions(+), 102 deletions(-) delete mode 100644 src/core_plugins/timelion/.eslintrc diff --git a/.eslintignore b/.eslintignore index 2482278de75cc..e62ae8c06a75a 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,5 @@ +/src/core_plugins/console/public/webpackShims +/src/core_plugins/console/public/tests/webpackShims /src/core_plugins/timelion/bower_components /src/core_plugins/timelion/vendor_components test/fixtures/scenarios diff --git a/.eslintrc b/.eslintrc index 7a623df06a6ca..1904222b3cfa9 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,2 +1,8 @@ --- extends: '@elastic/kibana' +rules: + no-unused-vars: off + no-var: off + prefer-const: off + no-extra-semi: off + quotes: off diff --git a/package.json b/package.json index b5425331a79c5..7dac431a9e428 100644 --- a/package.json +++ b/package.json @@ -163,16 +163,16 @@ "wreck": "6.2.0" }, "devDependencies": { - "@elastic/eslint-config-kibana": "0.0.3", + "@elastic/eslint-config-kibana": "0.2.0", "angular-mocks": "1.4.7", "auto-release-sinon": "1.0.3", - "babel-eslint": "4.1.8", "chai": "3.5.0", + "babel-eslint": "6.1.2", "chokidar": "1.6.0", "chromedriver": "2.24.1", "elasticdump": "2.1.1", - "eslint": "1.10.3", - "eslint-plugin-mocha": "1.1.0", + "eslint": "3.3.1", + "eslint-plugin-mocha": "4.4.0", "event-stream": "3.3.2", "expect.js": "0.3.1", "faker": "1.1.0", @@ -186,7 +186,7 @@ "grunt-karma": "2.0.0", "grunt-run": "0.6.0", "grunt-simple-mocha": "0.4.0", - "gruntify-eslint": "1.0.1", + "gruntify-eslint": "3.0.0", "gulp-sourcemaps": "1.7.3", "handlebars": "4.0.5", "husky": "0.8.1", diff --git a/src/core_plugins/console/.eslintrc b/src/core_plugins/console/.eslintrc index c5fcfc4ff6fda..f539f6cd5878f 100644 --- a/src/core_plugins/console/.eslintrc +++ b/src/core_plugins/console/.eslintrc @@ -1,34 +1,36 @@ --- root: true -extends: '@elastic/kibana' +extends: '../../../.eslintrc' rules: - block-scoped-var: [0] - camelcase: [0] - curly: [0] - dot-location: [0] - dot-notation: [0] - eqeqeq: [0] - guard-for-in: [0] - indent: [0] - max-len: [0] - new-cap: [0] - no-caller: [0] - no-empty: [0] - no-extend-native: [0] - no-loop-func: [0] - no-multi-str: [0] - no-nested-ternary: [0] - no-proto: [0] - no-sequences: [0] - no-undef: [0] - no-use-before-define: [0] - one-var: [0] - quotes: [0] - space-before-blocks: [0] - space-in-parens: [0] - space-infix-ops: [0] - semi: [0] - strict: [0] - wrap-iife: [0] + block-scoped-var: off + camelcase: off + curly: off + dot-location: off + dot-notation: off + eqeqeq: off + guard-for-in: off + indent: off + max-len: off + new-cap: off + no-caller: off + no-empty: off + no-extend-native: off + no-loop-func: off + no-multi-str: off + no-nested-ternary: off + no-proto: off + no-sequences: off + no-undef: off + no-use-before-define: off + one-var: off + quotes: off + space-before-blocks: off + space-in-parens: off + space-infix-ops: off + semi: off + strict: off + wrap-iife: off + no-var: off + prefer-const: off diff --git a/src/core_plugins/timelion/.eslintrc b/src/core_plugins/timelion/.eslintrc deleted file mode 100644 index 78ad50cf6a489..0000000000000 --- a/src/core_plugins/timelion/.eslintrc +++ /dev/null @@ -1,68 +0,0 @@ ---- -parser: babel-eslint - -env: - es6: true - amd: true - node: true - browser: true - jasmine: true - -rules: - block-scoped-var: 2 - camelcase: [ 2, { properties: never } ] - comma-dangle: 0 - comma-style: [ 2, last ] - consistent-return: 0 - curly: [ 2, multi-line ] - dot-location: [ 2, property ] - dot-notation: [ 2, { allowKeywords: true } ] - eqeqeq: [ 2, allow-null ] - guard-for-in: 2 - indent: [ 2, 2, { SwitchCase: 1 } ] - key-spacing: [ 0, { align: value } ] - max-len: [ 2, 140, 2, { ignoreComments: true, ignoreUrls: true } ] - new-cap: [ 2, { capIsNewExceptions: [ Private ] } ] - no-bitwise: 0 - no-caller: 2 - no-cond-assign: 0 - no-debugger: 2 - no-empty: 2 - no-eval: 2 - no-extend-native: 2 - no-extra-parens: 0 - no-irregular-whitespace: 2 - no-iterator: 2 - no-loop-func: 2 - no-multi-spaces: 0 - no-multi-str: 2 - no-nested-ternary: 2 - no-new: 0 - no-path-concat: 0 - no-proto: 2 - no-return-assign: 0 - no-script-url: 2 - no-sequences: 2 - no-shadow: 0 - no-trailing-spaces: 2 - no-undef: 2 - no-underscore-dangle: 0 - no-unused-expressions: 0 - no-unused-vars: 0 - no-use-before-define: [ 2, nofunc ] - no-with: 2 - one-var: [ 2, never ] - quotes: [ 2, single ] - semi-spacing: [ 2, { before: false, after: true } ] - semi: [ 2, always ] - space-after-keywords: [ 2, always ] - space-before-blocks: [ 2, always ] - space-before-function-paren: [ 2, { anonymous: always, named: never } ] - space-in-parens: [ 2, never ] - space-infix-ops: [ 2, { int32Hint: false } ] - space-return-throw-case: [ 2 ] - space-unary-ops: [ 2 ] - strict: [ 2, never ] - valid-typeof: 2 - wrap-iife: [ 2, outside ] - yoda: 0 From 70cb9d49af115c0e688783abdff64892fb9a814b Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 2 Sep 2016 14:33:02 -0700 Subject: [PATCH 02/33] replace gruntify-eslint with basic eslint-cli wrapper --- .eslintignore | 7 +++-- Gruntfile.js | 11 -------- tasks/config/eslint.js | 57 ++++++++++++++++++++------------------ tasks/eslint.js | 42 ++++++++++++++++++++++++++++ tasks/lint_staged_files.js | 26 +++++++++++++---- 5 files changed, 97 insertions(+), 46 deletions(-) create mode 100644 tasks/eslint.js diff --git a/.eslintignore b/.eslintignore index e62ae8c06a75a..5e30ee48846ae 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,7 +1,8 @@ +/optimize +/src/fixtures/vislib/mock_data +/src/ui/public/angular-bootstrap +/test/fixtures/scenarios /src/core_plugins/console/public/webpackShims /src/core_plugins/console/public/tests/webpackShims /src/core_plugins/timelion/bower_components /src/core_plugins/timelion/vendor_components -test/fixtures/scenarios -optimize -test/fixtures/scenarios diff --git a/Gruntfile.js b/Gruntfile.js index d4246608d8d21..f53ca0fe71a07 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -39,17 +39,6 @@ module.exports = function (grunt) { ' Licensed <%= package.license %> */\n' }, - lintThese: [ - 'Gruntfile.js', - '<%= root %>/tasks/**/*.js', - '<%= root %>/test/**/*.js', - '<%= src %>/**/*.js', - '!<%= src %>/ui/public/angular-bootstrap/**/*.js', - '!<%= src %>/core_plugins/timelion/bower_components/**/*.js', - '!<%= src %>/core_plugins/timelion/vendor_components/**/*.js', - '!<%= src %>/fixtures/**/*.js', - '!<%= root %>/test/fixtures/scenarios/**/*.js' - ], deepModules: { 'caniuse-db': '1.0.30000265', 'chalk': '1.1.0', diff --git a/tasks/config/eslint.js b/tasks/config/eslint.js index dbc1cea416969..46742b13ab05b 100644 --- a/tasks/config/eslint.js +++ b/tasks/config/eslint.js @@ -1,30 +1,33 @@ -var resolve = require('path').resolve; +import { resolve } from 'path'; +module.exports = grunt => ({ + options: { + paths: [ + 'Gruntfile.js', + 'bin', + 'config', + 'src', + 'tasks', + 'test', + 'utilities', + ], + }, -module.exports = function (grunt) { - return { - // just lint the source dir - source: { - options: { - cache: resolve(grunt.config.get('root'), '.eslint.fixSource.cache') - }, + source: { + options: { + cache: resolve(grunt.config.get('root'), '.eslint.fixSource.cache') + } + }, - files: { - src: '<%= lintThese %>' - } - }, + fixSource: { + options: { + cache: resolve(grunt.config.get('root'), '.eslint.fixSource.cache'), + fix: true + } + }, - // lint the source and fix any fixable errors - fixSource: { - options: { - cache: resolve(grunt.config.get('root'), '.eslint.fixSource.cache'), - fix: true - }, - - files: { - src: '<%= lintThese %>' - } - }, - - staged: {} - }; -}; + staged: { + options: { + paths: null // overridden by lintStagedFiles task + } + } +}); diff --git a/tasks/eslint.js b/tasks/eslint.js new file mode 100644 index 0000000000000..e5392e949fc7d --- /dev/null +++ b/tasks/eslint.js @@ -0,0 +1,42 @@ +import { CLIEngine } from 'eslint'; + +const OPTION_DEFAULTS = { + paths: null, + cache: null, + fix: false +}; + +module.exports = grunt => { + grunt.registerMultiTask('eslint',function () { + const options = this.options(OPTION_DEFAULTS); + + if (!options.paths) { + grunt.fatal(new Error('No eslint.options.paths specified')); + return; + } + + const cli = new CLIEngine({ + cache: options.cache, + fix: options.fix, + cwd: grunt.config.get('root'), + }); + + const report = cli.executeOnFiles(options.paths); + + // output fixes to disk + if (options.fix) { + CLIEngine.outputFixes(report); + } + + // log the formatted linting report + const formatter = cli.getFormatter(); + + const errTypes = []; + if (report.errorCount > 0) errTypes.push('errors'); + if (report.warningCount > 0) errTypes.push('warning'); + if (!errTypes.length) return; + + grunt.log.write(formatter(report.results)); + grunt.fatal(`eslint ${errTypes.join(' & ')}`); + }); +}; diff --git a/tasks/lint_staged_files.js b/tasks/lint_staged_files.js index e7c2f95752d13..d8117b62c2772 100644 --- a/tasks/lint_staged_files.js +++ b/tasks/lint_staged_files.js @@ -1,5 +1,7 @@ import { resolve } from 'path'; import { isStaged, getFilename } from './utils/files_to_commit'; +import { CLIEngine } from 'eslint'; +import minimatch from 'minimatch'; const root = resolve(__dirname, '..'); @@ -7,18 +9,32 @@ export default function (grunt) { grunt.registerTask('lintStagedFiles', function () { grunt.task.requires('collectFilesToCommit'); - // match these patterns - var patterns = grunt.config.get('eslint.source.files.src'); - if (!patterns) grunt.fail.warn('eslint file pattern is not defined'); + // convert eslint paths to globs + const cli = new CLIEngine(); + const eslintSourcePaths = grunt.config.get('eslint.options.paths'); + if (!eslintSourcePaths) grunt.fail.warn('eslint.options.paths is not defined'); + + const sourcePathRegexps = cli.resolveFileGlobPatterns(eslintSourcePaths) + .map(glob => minimatch.makeRe(glob)); const files = grunt.config .get('filesToCommit') .filter(isStaged) .map(getFilename) .map(file => resolve(root, file)) - .filter(file => grunt.file.isMatch(patterns, file)); + .filter(file => { + if (!sourcePathRegexps.some(re => file.match(re))) { + return false; + } + + if (cli.isPathIgnored(file)) { + return false; + } + + return true; + }); - grunt.config.set('eslint.staged.files.src', files); + grunt.config.set('eslint.staged.options.paths', files); grunt.task.run(['eslint:staged']); }); } From fdac53fdfeaaf1aa6ab62fe13a35300eef2eb98f Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 25 Aug 2016 10:47:57 -0700 Subject: [PATCH 03/33] arrow-IIFEs must be invoked outside of the parens --- src/cli/cluster/__tests__/_mock_cluster_fork.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/cluster/__tests__/_mock_cluster_fork.js b/src/cli/cluster/__tests__/_mock_cluster_fork.js index 2671ca08bdb9a..0915d172a4cd6 100644 --- a/src/cli/cluster/__tests__/_mock_cluster_fork.js +++ b/src/cli/cluster/__tests__/_mock_cluster_fork.js @@ -24,7 +24,7 @@ export default class MockClusterFork extends EventEmitter { dead = true; this.emit('exit'); cluster.emit('exit', this, this.exitCode || 0); - }()); + })(); }), }, isDead: sinon.spy(() => dead), @@ -39,6 +39,6 @@ export default class MockClusterFork extends EventEmitter { await wait(); dead = false; this.emit('online'); - }()); + })(); } } From c157202308c2c303362c15e006979e239f5606ca Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 25 Aug 2016 10:48:30 -0700 Subject: [PATCH 04/33] move import statements before their use --- src/ui/ui_bundle_collection.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ui/ui_bundle_collection.js b/src/ui/ui_bundle_collection.js index 3e652a176974c..a6b87779486b8 100644 --- a/src/ui/ui_bundle_collection.js +++ b/src/ui/ui_bundle_collection.js @@ -1,8 +1,3 @@ -const rimraf = promisify(require('rimraf')); -const mkdirp = promisify(require('mkdirp')); -const unlink = promisify(require('fs').unlink); -const readdir = promisify(require('fs').readdir); - import UiBundle from './ui_bundle'; import appEntryTemplate from './app_entry_template'; import { readFileSync as readSync } from 'fs'; @@ -11,6 +6,11 @@ import { join } from 'path'; import { resolve, promisify } from 'bluebird'; import { makeRe } from 'minimatch'; +const rimraf = promisify(require('rimraf')); +const mkdirp = promisify(require('mkdirp')); +const unlink = promisify(require('fs').unlink); +const readdir = promisify(require('fs').readdir); + class UiBundleCollection { constructor(bundlerEnv, filter) { this.each = []; From c10b2606efe34e44f131919e57b7d3630b21e989 Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 25 Aug 2016 10:49:47 -0700 Subject: [PATCH 05/33] reindent to satisfy new indentation check algorithm --- src/cli/cluster/cluster_manager.js | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/cli/cluster/cluster_manager.js b/src/cli/cluster/cluster_manager.js index 80b183cd663a6..1282d17442b02 100644 --- a/src/cli/cluster/cluster_manager.js +++ b/src/cli/cluster/cluster_manager.js @@ -86,19 +86,16 @@ module.exports = class ClusterManager { const chokidar = require('chokidar'); const fromRoot = require('../../utils/from_root'); - const watchPaths = uniq( - [ - fromRoot('src/core_plugins'), - fromRoot('src/server'), - fromRoot('src/ui'), - fromRoot('src/utils'), - fromRoot('config'), - ...extraPaths - ] - .map(path => resolve(path)) - ); - - this.watcher = chokidar.watch(watchPaths, { + const watchPaths = [ + fromRoot('src/core_plugins'), + fromRoot('src/server'), + fromRoot('src/ui'), + fromRoot('src/utils'), + fromRoot('config'), + ...extraPaths + ].map(path => resolve(path)); + + this.watcher = chokidar.watch(uniq(watchPaths), { cwd: fromRoot('.'), ignored: /[\\\/](\..*|node_modules|bower_components|public|__tests__)[\\\/]/ }); From 514551c0f53c1d2fbbdd4f182d10268ff0d0ba1f Mon Sep 17 00:00:00 2001 From: spalger Date: Tue, 6 Sep 2016 15:27:10 -0700 Subject: [PATCH 06/33] place missing semicolon --- src/fixtures/mock_ui_state.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fixtures/mock_ui_state.js b/src/fixtures/mock_ui_state.js index 50d913ae337e8..5f5b90e38eb3d 100644 --- a/src/fixtures/mock_ui_state.js +++ b/src/fixtures/mock_ui_state.js @@ -10,4 +10,4 @@ export default { }, on: _.noop, off: _.noop -} +}; From 76e3a4b9a3eeb1287bc07226cd1e367df181ba23 Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 4 Nov 2016 12:51:08 -0700 Subject: [PATCH 07/33] apply unwrap-simple-amd jscodeshift --- src/core_plugins/console/public/src/curl.js | 343 ++++++------ .../kibana/public/discover/_hit_sort_fn.js | 108 ++-- .../timelion/public/directives/docs.js | 123 +++-- .../public/services/saved_sheet_register.js | 8 +- .../timelion/public/services/saved_sheets.js | 134 +++-- src/core_plugins/timelion/public/vis/index.js | 53 +- .../public/vis/timelion_vis_controller.js | 116 ++-- .../vis/timelion_vis_params_controller.js | 18 +- src/fixtures/agg_resp/date_histogram.js | 500 +++++++++--------- .../hierarchical/_collect_branch.js | 62 ++- .../agg_response/point_series/_init_x_axis.js | 26 +- src/ui/public/filter_bar/lib/map_script.js | 46 +- src/ui/public/utils/add_word_breaks.js | 86 ++- src/ui/public/utils/es_bool.js | 36 +- src/ui/public/utils/ipv4_address.js | 76 ++- src/ui/public/utils/mapping_setup.js | 182 ++++--- src/ui/public/vis/agg_config_result.js | 76 ++- .../vislib/components/color/seed_colors.js | 31 +- .../components/labels/pie/return_pie_names.js | 28 +- .../zero_injection/zero_filled_array.js | 39 +- .../layout/splits/column_chart/chart_split.js | 87 ++- .../splits/column_chart/chart_title_split.js | 62 ++- .../splits/column_chart/x_axis_split.js | 39 +- .../splits/column_chart/y_axis_split.js | 79 ++- .../layout/splits/pie_chart/chart_split.js | 87 ++- .../splits/pie_chart/chart_title_split.js | 61 ++- .../lib/layout/splits/tile_map/map_split.js | 93 ++-- test/functional/index.js | 92 ++-- test/intern.js | 39 +- test/intern_visual_regression.js | 43 +- test/unit/api/ingest/_field_capabilities.js | 130 +++-- test/unit/api/ingest/_processors.js | 28 +- test/unit/api/ingest/_simulate.js | 276 +++++----- test/unit/api/ingest/index.js | 50 +- test/unit/api/ingest/processors/_append.js | 116 ++-- test/unit/api/ingest/processors/_convert.js | 122 +++-- test/unit/api/ingest/processors/_date.js | 156 +++--- test/unit/api/ingest/processors/_geoip.js | 124 +++-- test/unit/api/ingest/processors/_grok.js | 122 +++-- test/unit/api/ingest/processors/_gsub.js | 118 ++--- test/unit/api/ingest/processors/_join.js | 110 ++-- test/unit/api/ingest/processors/_lowercase.js | 106 ++-- test/unit/api/ingest/processors/_remove.js | 106 ++-- test/unit/api/ingest/processors/_rename.js | 112 ++-- test/unit/api/ingest/processors/_set.js | 116 ++-- test/unit/api/ingest/processors/_split.js | 110 ++-- test/unit/api/ingest/processors/_trim.js | 106 ++-- test/unit/api/ingest/processors/_uppercase.js | 106 ++-- test/unit/api/ingest/processors/index.js | 63 ++- test/unit/api/scripts/_languages.js | 38 +- test/unit/api/scripts/index.js | 18 +- test/unit/api/search/_count.js | 100 ++-- test/unit/api/search/index.js | 34 +- test/visual_regression/index.js | 36 +- 54 files changed, 2533 insertions(+), 2643 deletions(-) diff --git a/src/core_plugins/console/public/src/curl.js b/src/core_plugins/console/public/src/curl.js index 7cfa4d282a6c2..881039fd869ef 100644 --- a/src/core_plugins/console/public/src/curl.js +++ b/src/core_plugins/console/public/src/curl.js @@ -1,217 +1,214 @@ -define(function () { - 'use strict'; +'use strict'; - function detectCURLinLine(line) { - // returns true if text matches a curl request - return line.match(/^\s*?curl\s+(-X[A-Z]+)?\s*['"]?.*?['"]?(\s*$|\s+?-d\s*?['"])/); +function detectCURLinLine(line) { + // returns true if text matches a curl request + return line.match(/^\s*?curl\s+(-X[A-Z]+)?\s*['"]?.*?['"]?(\s*$|\s+?-d\s*?['"])/); - } +} - function detectCURL(text) { - // returns true if text matches a curl request - if (!text) return false; - for (var line of text.split("\n")) { - if (detectCURLinLine(line)) { - return true; - } +function detectCURL(text) { + // returns true if text matches a curl request + if (!text) return false; + for (var line of text.split("\n")) { + if (detectCURLinLine(line)) { + return true; } - return false; + } + return false; +} + +function parseCURL(text) { + var state = 'NONE'; + var out = []; + var body = []; + var line = ''; + var lines = text.trim().split("\n"); + var matches; + + var EmptyLine = /^\s*$/; + var Comment = /^\s*(?:#|\/{2,})(.*)\n?$/; + var ExecutionComment = /^\s*#!/; + var ClosingSingleQuote = /^([^']*)'/; + var ClosingDoubleQuote = /^((?:[^\\"]|\\.)*)"/; + var EscapedQuotes = /^((?:[^\\"']|\\.)+)/; + + var LooksLikeCurl = /^\s*curl\s+/; + var CurlVerb = /-X ?(GET|HEAD|POST|PUT|DELETE)/; + + var HasProtocol = /[\s"']https?:\/\//; + var CurlRequestWithProto = /[\s"']https?:\/\/[^\/ ]+\/+([^\s"']+)/; + var CurlRequestWithoutProto = /[\s"'][^\/ ]+\/+([^\s"']+)/; + var CurlData = /^.+\s(--data|-d)\s*/; + var SenseLine = /^\s*(GET|HEAD|POST|PUT|DELETE)\s+\/?(.+)/; + + if (lines.length > 0 && ExecutionComment.test(lines[0])) { + lines.shift(); } - function parseCURL(text) { - var state = 'NONE'; - var out = []; - var body = []; - var line = ''; - var lines = text.trim().split("\n"); - var matches; - - var EmptyLine = /^\s*$/; - var Comment = /^\s*(?:#|\/{2,})(.*)\n?$/; - var ExecutionComment = /^\s*#!/; - var ClosingSingleQuote = /^([^']*)'/; - var ClosingDoubleQuote = /^((?:[^\\"]|\\.)*)"/; - var EscapedQuotes = /^((?:[^\\"']|\\.)+)/; - - var LooksLikeCurl = /^\s*curl\s+/; - var CurlVerb = /-X ?(GET|HEAD|POST|PUT|DELETE)/; + function nextLine() { + if (line.length > 0) { + return true; + } + if (lines.length == 0) { + return false; + } + line = lines.shift().replace(/[\r\n]+/g, "\n") + "\n"; + return true; + } - var HasProtocol = /[\s"']https?:\/\//; - var CurlRequestWithProto = /[\s"']https?:\/\/[^\/ ]+\/+([^\s"']+)/; - var CurlRequestWithoutProto = /[\s"'][^\/ ]+\/+([^\s"']+)/; - var CurlData = /^.+\s(--data|-d)\s*/; - var SenseLine = /^\s*(GET|HEAD|POST|PUT|DELETE)\s+\/?(.+)/; + function unescapeLastBodyEl() { + var str = body.pop().replace(/\\([\\"'])/g, "$1"); + body.push(str); + } - if (lines.length > 0 && ExecutionComment.test(lines[0])) { - lines.shift(); + // Is the next char a single or double quote? + // If so remove it + function detectQuote() { + if (line.substr(0, 1) == "'") { + line = line.substr(1); + state = 'SINGLE_QUOTE'; } - - function nextLine() { - if (line.length > 0) { - return true; - } - if (lines.length == 0) { - return false; - } - line = lines.shift().replace(/[\r\n]+/g, "\n") + "\n"; - return true; + else if (line.substr(0, 1) == '"') { + line = line.substr(1); + state = 'DOUBLE_QUOTE'; } - - function unescapeLastBodyEl() { - var str = body.pop().replace(/\\([\\"'])/g, "$1"); - body.push(str); + else { + state = 'UNQUOTED'; } + } - // Is the next char a single or double quote? - // If so remove it - function detectQuote() { - if (line.substr(0, 1) == "'") { - line = line.substr(1); - state = 'SINGLE_QUOTE'; - } - else if (line.substr(0, 1) == '"') { - line = line.substr(1); - state = 'DOUBLE_QUOTE'; - } - else { - state = 'UNQUOTED'; - } + // Body is finished - append to output with final LF + function addBodyToOut() { + if (body.length > 0) { + out.push(body.join("")); + body = []; } + state = 'LF'; + out.push("\n"); + } - // Body is finished - append to output with final LF - function addBodyToOut() { - if (body.length > 0) { - out.push(body.join("")); - body = []; - } - state = 'LF'; - out.push("\n"); - } - - // If the pattern matches, then the state is about to change, - // so add the capture to the body and detect the next state - // Otherwise add the whole line - function consumeMatching(pattern) { - var matches = line.match(pattern); - if (matches) { - body.push(matches[1]); - line = line.substr(matches[0].length); - detectQuote(); - } - else { - body.push(line); - line = ''; - } + // If the pattern matches, then the state is about to change, + // so add the capture to the body and detect the next state + // Otherwise add the whole line + function consumeMatching(pattern) { + var matches = line.match(pattern); + if (matches) { + body.push(matches[1]); + line = line.substr(matches[0].length); + detectQuote(); + } + else { + body.push(line); + line = ''; } + } - function parseCurlLine() { - var verb = 'GET'; - var request = ''; - var matches; - if (matches = line.match(CurlVerb)) { - verb = matches[1]; - } + function parseCurlLine() { + var verb = 'GET'; + var request = ''; + var matches; + if (matches = line.match(CurlVerb)) { + verb = matches[1]; + } - // JS regexen don't support possesive quantifiers, so - // we need two distinct patterns - var pattern = HasProtocol.test(line) - ? CurlRequestWithProto - : CurlRequestWithoutProto; + // JS regexen don't support possesive quantifiers, so + // we need two distinct patterns + var pattern = HasProtocol.test(line) + ? CurlRequestWithProto + : CurlRequestWithoutProto; - if (matches = line.match(pattern)) { - request = matches[1]; - } + if (matches = line.match(pattern)) { + request = matches[1]; + } - out.push(verb + ' /' + request + "\n"); + out.push(verb + ' /' + request + "\n"); - if (matches = line.match(CurlData)) { - line = line.substr(matches[0].length); - detectQuote(); - if (EmptyLine.test(line)) { - line = ''; - } - } - else { - state = 'NONE'; + if (matches = line.match(CurlData)) { + line = line.substr(matches[0].length); + detectQuote(); + if (EmptyLine.test(line)) { line = ''; - out.push(''); } } + else { + state = 'NONE'; + line = ''; + out.push(''); + } + } - while (nextLine()) { + while (nextLine()) { - if (state == 'SINGLE_QUOTE') { - consumeMatching(ClosingSingleQuote); - } + if (state == 'SINGLE_QUOTE') { + consumeMatching(ClosingSingleQuote); + } - else if (state == 'DOUBLE_QUOTE') { - consumeMatching(ClosingDoubleQuote); + else if (state == 'DOUBLE_QUOTE') { + consumeMatching(ClosingDoubleQuote); + unescapeLastBodyEl(); + } + + else if (state == 'UNQUOTED') { + consumeMatching(EscapedQuotes); + if (body.length) { unescapeLastBodyEl(); } - - else if (state == 'UNQUOTED') { - consumeMatching(EscapedQuotes); - if (body.length) { - unescapeLastBodyEl(); - } - if (state == 'UNQUOTED') { - addBodyToOut(); - line = '' - } + if (state == 'UNQUOTED') { + addBodyToOut(); + line = '' } + } - // the BODY state (used to match the body of a Sense request) - // can be terminated early if it encounters - // a comment or an empty line - else if (state == 'BODY') { - if (Comment.test(line) || EmptyLine.test(line)) { - addBodyToOut(); - } - else { - body.push(line); - line = ''; - } + // the BODY state (used to match the body of a Sense request) + // can be terminated early if it encounters + // a comment or an empty line + else if (state == 'BODY') { + if (Comment.test(line) || EmptyLine.test(line)) { + addBodyToOut(); } - - else if (EmptyLine.test(line)) { - if (state != 'LF') { - out.push("\n"); - state = 'LF'; - } + else { + body.push(line); line = ''; } + } - else if (matches = line.match(Comment)) { - out.push("#" + matches[1] + "\n"); - state = 'NONE'; - line = ''; + else if (EmptyLine.test(line)) { + if (state != 'LF') { + out.push("\n"); + state = 'LF'; } + line = ''; + } - else if (LooksLikeCurl.test(line)) { - parseCurlLine(); - } + else if (matches = line.match(Comment)) { + out.push("#" + matches[1] + "\n"); + state = 'NONE'; + line = ''; + } - else if (matches = line.match(SenseLine)) { - out.push(matches[1] + ' /' + matches[2] + "\n"); - line = ''; - state = 'BODY'; - } + else if (LooksLikeCurl.test(line)) { + parseCurlLine(); + } - // Nothing else matches, so output with a prefix of !!! for debugging purposes - else { - out.push('### ' + line); - line = ''; - } + else if (matches = line.match(SenseLine)) { + out.push(matches[1] + ' /' + matches[2] + "\n"); + line = ''; + state = 'BODY'; } - addBodyToOut(); - return out.join('').trim(); + // Nothing else matches, so output with a prefix of !!! for debugging purposes + else { + out.push('### ' + line); + line = ''; + } } + addBodyToOut(); + return out.join('').trim(); +} - return { - parseCURL: parseCURL, - detectCURL: detectCURL - }; -}); +export default { + parseCURL: parseCURL, + detectCURL: detectCURL +}; diff --git a/src/core_plugins/kibana/public/discover/_hit_sort_fn.js b/src/core_plugins/kibana/public/discover/_hit_sort_fn.js index 83cc68c160504..eb84df5f507cc 100644 --- a/src/core_plugins/kibana/public/discover/_hit_sort_fn.js +++ b/src/core_plugins/kibana/public/discover/_hit_sort_fn.js @@ -1,66 +1,64 @@ -define(function () { - return function HitSortFnFactory() { +export default function HitSortFnFactory() { - /** - * Creates a sort function that will resort hits based on the value - * es used to sort them. - * - * background: - * When a hit is sorted by elasticsearch, es will write the values that it used - * to sort them into an array at the top level of the hit like so - * - * ``` - * hits: { - * total: x, - * hits: [ - * { - * _id: i, - * _source: {}, - * sort: [ - * // all values used to sort, in the order of precidance - * ] - * } - * ] - * }; - * ``` - * - * @param {[type]} field [description] - * @param {[type]} direction [description] - * @return {[type]} [description] - */ - return function createHitSortFn(direction) { - const descending = (direction === 'desc'); + /** + * Creates a sort function that will resort hits based on the value + * es used to sort them. + * + * background: + * When a hit is sorted by elasticsearch, es will write the values that it used + * to sort them into an array at the top level of the hit like so + * + * ``` + * hits: { + * total: x, + * hits: [ + * { + * _id: i, + * _source: {}, + * sort: [ + * // all values used to sort, in the order of precidance + * ] + * } + * ] + * }; + * ``` + * + * @param {[type]} field [description] + * @param {[type]} direction [description] + * @return {[type]} [description] + */ + return function createHitSortFn(direction) { + const descending = (direction === 'desc'); - return function sortHits(hitA, hitB) { - let bBelowa = null; + return function sortHits(hitA, hitB) { + let bBelowa = null; - const aSorts = hitA.sort || []; - const bSorts = hitB.sort || []; + const aSorts = hitA.sort || []; + const bSorts = hitB.sort || []; - // walk each sort value, and compair until one is different - for (let i = 0; i < bSorts.length; i++) { - const a = aSorts[i]; - const b = bSorts[i]; + // walk each sort value, and compair until one is different + for (let i = 0; i < bSorts.length; i++) { + const a = aSorts[i]; + const b = bSorts[i]; - if (a == null || b > a) { - bBelowa = !descending; - break; - } - - if (b < a) { - bBelowa = descending; - break; - } + if (a == null || b > a) { + bBelowa = !descending; + break; } - if (bBelowa !== null) { - return bBelowa ? -1 : 1; - } else { - return 0; + if (b < a) { + bBelowa = descending; + break; } + } - }; - }; + if (bBelowa !== null) { + return bBelowa ? -1 : 1; + } else { + return 0; + } + }; }; -}); + +}; diff --git a/src/core_plugins/timelion/public/directives/docs.js b/src/core_plugins/timelion/public/directives/docs.js index 40d938adedd48..e7390e105043b 100644 --- a/src/core_plugins/timelion/public/directives/docs.js +++ b/src/core_plugins/timelion/public/directives/docs.js @@ -1,70 +1,67 @@ -define(function (require) { - var html = require('../partials/docs/tutorial.html'); - var app = require('ui/modules').get('apps/timelion', []); - var _ = require('lodash'); - var moment = require('moment'); +var html = require('../partials/docs/tutorial.html'); +var app = require('ui/modules').get('apps/timelion', []); +var _ = require('lodash'); +var moment = require('moment'); - app.directive('timelionDocs', function (config, $http) { - return { - restrict: 'E', - template: html, - controller: function ($scope, config) { - $scope.section = config.get('timelion:showTutorial', true) ? 'tutorial' : 'functions'; - $scope.page = 1; - $scope.functions = { - list: [], - details: null - }; - - function init() { - $scope.es = { - invalidCount: 0 - }; - getFunctions(); - checkElasticsearch(); - }; +app.directive('timelionDocs', function (config, $http) { + return { + restrict: 'E', + template: html, + controller: function ($scope, config) { + $scope.section = config.get('timelion:showTutorial', true) ? 'tutorial' : 'functions'; + $scope.page = 1; + $scope.functions = { + list: [], + details: null + }; - function getFunctions() { - return $http.get('../api/timelion/functions').then(function (resp) { - $scope.functions.list = resp.data; - }); - } - $scope.recheckElasticsearch = function () { - $scope.es.valid = null; - checkElasticsearch().then(function (valid) { - if (!valid) $scope.es.invalidCount++; - }); + function init() { + $scope.es = { + invalidCount: 0 }; + getFunctions(); + checkElasticsearch(); + }; - function checkElasticsearch() { - return $http.get('../api/timelion/validate/es').then(function (resp) { - if (resp.data.ok) { - - $scope.es.valid = true; - $scope.es.stats = { - min: moment(resp.data.min).format('LLL'), - max: moment(resp.data.max).format('LLL'), - field: resp.data.field - }; - } else { - $scope.es.valid = false; - $scope.es.invalidReason = (function () { - try { - var esResp = JSON.parse(resp.data.resp.response); - return _.get(esResp, 'error.root_cause[0].reason'); - } catch (e) { - if (_.get(resp, 'data.resp.message')) return _.get(resp, 'data.resp.message'); - if (_.get(resp, 'data.resp.output.payload.message')) return _.get(resp, 'data.resp.output.payload.message'); - return 'Unknown error'; - } - }()); - } - return $scope.es.valid; - }); - }; - init(); + function getFunctions() { + return $http.get('../api/timelion/functions').then(function (resp) { + $scope.functions.list = resp.data; + }); } - }; - }); + $scope.recheckElasticsearch = function () { + $scope.es.valid = null; + checkElasticsearch().then(function (valid) { + if (!valid) $scope.es.invalidCount++; + }); + }; + + function checkElasticsearch() { + return $http.get('../api/timelion/validate/es').then(function (resp) { + if (resp.data.ok) { + $scope.es.valid = true; + $scope.es.stats = { + min: moment(resp.data.min).format('LLL'), + max: moment(resp.data.max).format('LLL'), + field: resp.data.field + }; + } else { + $scope.es.valid = false; + $scope.es.invalidReason = (function () { + try { + var esResp = JSON.parse(resp.data.resp.response); + return _.get(esResp, 'error.root_cause[0].reason'); + } catch (e) { + if (_.get(resp, 'data.resp.message')) return _.get(resp, 'data.resp.message'); + if (_.get(resp, 'data.resp.output.payload.message')) return _.get(resp, 'data.resp.output.payload.message'); + return 'Unknown error'; + } + }()); + } + return $scope.es.valid; + }); + }; + init(); + } + }; }); diff --git a/src/core_plugins/timelion/public/services/saved_sheet_register.js b/src/core_plugins/timelion/public/services/saved_sheet_register.js index 4716d0134f664..d735a8433510f 100644 --- a/src/core_plugins/timelion/public/services/saved_sheet_register.js +++ b/src/core_plugins/timelion/public/services/saved_sheet_register.js @@ -1,5 +1,3 @@ -define(function (require) { - return function savedSearchObjectFn(savedSheets) { - return savedSheets; - }; -}); +export default function savedSearchObjectFn(savedSheets) { + return savedSheets; +}; diff --git a/src/core_plugins/timelion/public/services/saved_sheets.js b/src/core_plugins/timelion/public/services/saved_sheets.js index 53f6e0616ed3a..8586fe87429a9 100644 --- a/src/core_plugins/timelion/public/services/saved_sheets.js +++ b/src/core_plugins/timelion/public/services/saved_sheets.js @@ -1,79 +1,77 @@ -define(function (require) { - var module = require('ui/modules').get('app/sheet'); - var _ = require('lodash'); - // bring in the factory - require('./_saved_sheet.js'); +var module = require('ui/modules').get('app/sheet'); +var _ = require('lodash'); +// bring in the factory +require('./_saved_sheet.js'); - // Register this service with the saved object registry so it can be - // edited by the object editor. - require('plugins/kibana/management/saved_object_registry').register({ - service: 'savedSheets', - title: 'sheets' - }); +// Register this service with the saved object registry so it can be +// edited by the object editor. +require('plugins/kibana/management/saved_object_registry').register({ + service: 'savedSheets', + title: 'sheets' +}); - // This is the only thing that gets injected into controllers - module.service('savedSheets', function (Promise, SavedSheet, kbnIndex, es, kbnUrl) { - this.type = SavedSheet.type; - this.Class = SavedSheet; +// This is the only thing that gets injected into controllers +module.service('savedSheets', function (Promise, SavedSheet, kbnIndex, es, kbnUrl) { + this.type = SavedSheet.type; + this.Class = SavedSheet; - this.loaderProperties = { - name: 'timelion-sheet', - noun: 'Saved Sheets', - nouns: 'saved sheets' - }; + this.loaderProperties = { + name: 'timelion-sheet', + noun: 'Saved Sheets', + nouns: 'saved sheets' + }; - // Returns a single sheet by ID, should be the name of the sheet - this.get = function (id) { - // Returns a promise that contains a sheet which is a subclass of docSource - return (new SavedSheet(id)).init(); - }; + // Returns a single sheet by ID, should be the name of the sheet + this.get = function (id) { + // Returns a promise that contains a sheet which is a subclass of docSource + return (new SavedSheet(id)).init(); + }; - this.urlFor = function (id) { - return kbnUrl.eval('#/{{id}}', {id: id}); - }; + this.urlFor = function (id) { + return kbnUrl.eval('#/{{id}}', {id: id}); + }; - this.delete = function (ids) { - ids = !_.isArray(ids) ? [ids] : ids; - return Promise.map(ids, function (id) { - return (new SavedSheet(id)).delete(); - }); - }; + this.delete = function (ids) { + ids = !_.isArray(ids) ? [ids] : ids; + return Promise.map(ids, function (id) { + return (new SavedSheet(id)).delete(); + }); + }; - this.find = function (searchString) { - var self = this; - var body; - if (searchString) { - body = { - query: { - simple_query_string: { - query: searchString + '*', - fields: ['title^3', 'description'], - default_operator: 'AND' - } + this.find = function (searchString) { + var self = this; + var body; + if (searchString) { + body = { + query: { + simple_query_string: { + query: searchString + '*', + fields: ['title^3', 'description'], + default_operator: 'AND' } - }; - } else { - body = { query: {match_all: {}}}; - } + } + }; + } else { + body = { query: {match_all: {}}}; + } - return es.search({ - index: kbnIndex, - type: 'timelion-sheet', - body: body, - size: 1000 - }) - .then(function (resp) { - return { - total: resp.hits.total, - hits: resp.hits.hits.map(function (hit) { - var source = hit._source; - source.id = hit._id; - source.url = self.urlFor(hit._id); - return source; - }) - }; - }); - }; - }); + return es.search({ + index: kbnIndex, + type: 'timelion-sheet', + body: body, + size: 1000 + }) + .then(function (resp) { + return { + total: resp.hits.total, + hits: resp.hits.hits.map(function (hit) { + var source = hit._source; + source.id = hit._id; + source.url = self.urlFor(hit._id); + return source; + }) + }; + }); + }; }); diff --git a/src/core_plugins/timelion/public/vis/index.js b/src/core_plugins/timelion/public/vis/index.js index afcad2bd2a3c1..56eb15bc1c3dc 100644 --- a/src/core_plugins/timelion/public/vis/index.js +++ b/src/core_plugins/timelion/public/vis/index.js @@ -1,33 +1,30 @@ -define(function (require) { - // we also need to load the controller and used by the template - require('plugins/timelion/vis/timelion_vis_controller'); - require('plugins/timelion/vis/timelion_vis_params_controller'); +// we also need to load the controller and used by the template +require('plugins/timelion/vis/timelion_vis_controller'); +require('plugins/timelion/vis/timelion_vis_params_controller'); - // Stylin - require('plugins/timelion/vis/timelion_vis.less'); +// Stylin +require('plugins/timelion/vis/timelion_vis.less'); - // register the provider with the visTypes registry so that other know it exists - require('ui/registry/vis_types').register(TimelionVisProvider); +// register the provider with the visTypes registry so that other know it exists +require('ui/registry/vis_types').register(TimelionVisProvider); - function TimelionVisProvider(Private) { - var TemplateVisType = Private(require('ui/template_vis_type')); +function TimelionVisProvider(Private) { + var TemplateVisType = Private(require('ui/template_vis_type')); - // return the visType object, which kibana will use to display and configure new - // Vis object of this type. - return new TemplateVisType({ - name: 'timelion', - title: 'Timeseries', - icon: 'fa-clock-o', - description: 'Create timeseries charts using the timelion expression language. ' + - 'Perfect for computing and combining timeseries set with functions suchs as derivatives and moving averages', - template: require('plugins/timelion/vis/timelion_vis.html'), - params: { - editor: require('plugins/timelion/vis/timelion_vis_params.html') - }, - requiresSearch: false - }); - } + // return the visType object, which kibana will use to display and configure new + // Vis object of this type. + return new TemplateVisType({ + name: 'timelion', + title: 'Timeseries', + icon: 'fa-clock-o', + description: 'Create timeseries charts using the timelion expression language. ' + + 'Perfect for computing and combining timeseries set with functions suchs as derivatives and moving averages', + template: require('plugins/timelion/vis/timelion_vis.html'), + params: { + editor: require('plugins/timelion/vis/timelion_vis_params.html') + }, + requiresSearch: false + }); +} - // export the provider so that the visType can be required with Private() - return TimelionVisProvider; -}); +export default TimelionVisProvider; diff --git a/src/core_plugins/timelion/public/vis/timelion_vis_controller.js b/src/core_plugins/timelion/public/vis/timelion_vis_controller.js index 4de140da70c8f..9996effc5e07a 100644 --- a/src/core_plugins/timelion/public/vis/timelion_vis_controller.js +++ b/src/core_plugins/timelion/public/vis/timelion_vis_controller.js @@ -1,63 +1,61 @@ -define(function (require) { - require('plugins/timelion/directives/chart/chart'); - require('plugins/timelion/directives/interval/interval'); - require('plugins/timelion/directives/refresh_hack'); - require('ui/state_management/app_state'); - - var _ = require('lodash'); - var module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); - module.controller('TimelionVisController', function ($scope, Private, Notifier, $http, $rootScope, timefilter, getAppState) { - var queryFilter = Private(require('ui/filter_bar/query_filter')); - var timezone = Private(require('plugins/timelion/services/timezone'))(); - var dashboardContext = Private(require('plugins/timelion/services/dashboard_context')); - - var notify = new Notifier({ - location: 'Timelion' +require('plugins/timelion/directives/chart/chart'); +require('plugins/timelion/directives/interval/interval'); +require('plugins/timelion/directives/refresh_hack'); +require('ui/state_management/app_state'); + +var _ = require('lodash'); +var module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); +module.controller('TimelionVisController', function ($scope, Private, Notifier, $http, $rootScope, timefilter, getAppState) { + var queryFilter = Private(require('ui/filter_bar/query_filter')); + var timezone = Private(require('plugins/timelion/services/timezone'))(); + var dashboardContext = Private(require('plugins/timelion/services/dashboard_context')); + + var notify = new Notifier({ + location: 'Timelion' + }); + + $scope.search = function run() { + var expression = $scope.vis.params.expression; + if (!expression) return; + + $http.post('../api/timelion/run', { + sheet: [expression], + extended: { + es: { + filter: dashboardContext() + } + }, + time: _.extend(timefilter.time, { + interval: $scope.vis.params.interval, + timezone: timezone + }), + }) + // data, status, headers, config + .success(function (resp) { + $scope.sheet = resp.sheet; + }) + .error(function (resp) { + $scope.sheet = []; + var err = new Error(resp.message); + err.stack = resp.stack; + notify.error(err); }); + }; - $scope.search = function run() { - var expression = $scope.vis.params.expression; - if (!expression) return; - - $http.post('../api/timelion/run', { - sheet: [expression], - extended: { - es: { - filter: dashboardContext() - } - }, - time: _.extend(timefilter.time, { - interval: $scope.vis.params.interval, - timezone: timezone - }), - }) - // data, status, headers, config - .success(function (resp) { - $scope.sheet = resp.sheet; - }) - .error(function (resp) { - $scope.sheet = []; - var err = new Error(resp.message); - err.stack = resp.stack; - notify.error(err); - }); - }; - - // This is bad, there should be a single event that triggers a refresh of data. - - // When the expression updates - $scope.$watchMulti(['vis.params.expression', 'vis.params.interval'], $scope.search); - - // When the time filter changes - $scope.$listen(timefilter, 'fetch', $scope.search); - - // When a filter is added to the filter bar? - $scope.$listen(queryFilter, 'fetch', $scope.search); - - // When auto refresh happens - $scope.$on('courier:searchRefresh', $scope.search); - - $scope.$on('fetch', $scope.search); + // This is bad, there should be a single event that triggers a refresh of data. + + // When the expression updates + $scope.$watchMulti(['vis.params.expression', 'vis.params.interval'], $scope.search); + + // When the time filter changes + $scope.$listen(timefilter, 'fetch', $scope.search); + + // When a filter is added to the filter bar? + $scope.$listen(queryFilter, 'fetch', $scope.search); + + // When auto refresh happens + $scope.$on('courier:searchRefresh', $scope.search); + + $scope.$on('fetch', $scope.search); - }); }); diff --git a/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js b/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js index 6cad50894d60a..1eaf89623aed7 100644 --- a/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js +++ b/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js @@ -1,14 +1,12 @@ -define(function (require) { - require('plugins/timelion/directives/expression_directive'); +require('plugins/timelion/directives/expression_directive'); - var module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); - module.controller('TimelionVisParamsController', function ($scope, $rootScope) { - $scope.vis.params.expression = $scope.vis.params.expression || '.es(*)'; - $scope.vis.params.interval = $scope.vis.params.interval || '1m'; +var module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); +module.controller('TimelionVisParamsController', function ($scope, $rootScope) { + $scope.vis.params.expression = $scope.vis.params.expression || '.es(*)'; + $scope.vis.params.interval = $scope.vis.params.interval || '1m'; - $scope.search = function () { - $rootScope.$broadcast('courier:searchRefresh'); - }; - }); + $scope.search = function () { + $rootScope.$broadcast('courier:searchRefresh'); + }; }); diff --git a/src/fixtures/agg_resp/date_histogram.js b/src/fixtures/agg_resp/date_histogram.js index 3c66a87dd4bec..d163f03fb8ef5 100644 --- a/src/fixtures/agg_resp/date_histogram.js +++ b/src/fixtures/agg_resp/date_histogram.js @@ -1,252 +1,250 @@ -define(function () { - return { - 'took': 35, - 'timed_out': false, - '_shards': { - 'total': 2, - 'successful': 2, - 'failed': 0 - }, - 'hits': { - 'total': 32899, - 'max_score': 0, - 'hits': [] - }, - 'aggregations': { - '1': { - 'buckets': [ - { - 'key_as_string': '2015-01-30T01:00:00.000Z', - 'key': 1422579600000, - 'doc_count': 18 - }, - { - 'key_as_string': '2015-01-30T02:00:00.000Z', - 'key': 1422583200000, - 'doc_count': 68 - }, - { - 'key_as_string': '2015-01-30T03:00:00.000Z', - 'key': 1422586800000, - 'doc_count': 146 - }, - { - 'key_as_string': '2015-01-30T04:00:00.000Z', - 'key': 1422590400000, - 'doc_count': 149 - }, - { - 'key_as_string': '2015-01-30T05:00:00.000Z', - 'key': 1422594000000, - 'doc_count': 363 - }, - { - 'key_as_string': '2015-01-30T06:00:00.000Z', - 'key': 1422597600000, - 'doc_count': 555 - }, - { - 'key_as_string': '2015-01-30T07:00:00.000Z', - 'key': 1422601200000, - 'doc_count': 878 - }, - { - 'key_as_string': '2015-01-30T08:00:00.000Z', - 'key': 1422604800000, - 'doc_count': 1133 - }, - { - 'key_as_string': '2015-01-30T09:00:00.000Z', - 'key': 1422608400000, - 'doc_count': 1438 - }, - { - 'key_as_string': '2015-01-30T10:00:00.000Z', - 'key': 1422612000000, - 'doc_count': 1719 - }, - { - 'key_as_string': '2015-01-30T11:00:00.000Z', - 'key': 1422615600000, - 'doc_count': 1813 - }, - { - 'key_as_string': '2015-01-30T12:00:00.000Z', - 'key': 1422619200000, - 'doc_count': 1790 - }, - { - 'key_as_string': '2015-01-30T13:00:00.000Z', - 'key': 1422622800000, - 'doc_count': 1582 - }, - { - 'key_as_string': '2015-01-30T14:00:00.000Z', - 'key': 1422626400000, - 'doc_count': 1439 - }, - { - 'key_as_string': '2015-01-30T15:00:00.000Z', - 'key': 1422630000000, - 'doc_count': 1154 - }, - { - 'key_as_string': '2015-01-30T16:00:00.000Z', - 'key': 1422633600000, - 'doc_count': 847 - }, - { - 'key_as_string': '2015-01-30T17:00:00.000Z', - 'key': 1422637200000, - 'doc_count': 588 - }, - { - 'key_as_string': '2015-01-30T18:00:00.000Z', - 'key': 1422640800000, - 'doc_count': 374 - }, - { - 'key_as_string': '2015-01-30T19:00:00.000Z', - 'key': 1422644400000, - 'doc_count': 152 - }, - { - 'key_as_string': '2015-01-30T20:00:00.000Z', - 'key': 1422648000000, - 'doc_count': 140 - }, - { - 'key_as_string': '2015-01-30T21:00:00.000Z', - 'key': 1422651600000, - 'doc_count': 73 - }, - { - 'key_as_string': '2015-01-30T22:00:00.000Z', - 'key': 1422655200000, - 'doc_count': 28 - }, - { - 'key_as_string': '2015-01-30T23:00:00.000Z', - 'key': 1422658800000, - 'doc_count': 9 - }, - { - 'key_as_string': '2015-01-31T00:00:00.000Z', - 'key': 1422662400000, - 'doc_count': 29 - }, - { - 'key_as_string': '2015-01-31T01:00:00.000Z', - 'key': 1422666000000, - 'doc_count': 38 - }, - { - 'key_as_string': '2015-01-31T02:00:00.000Z', - 'key': 1422669600000, - 'doc_count': 70 - }, - { - 'key_as_string': '2015-01-31T03:00:00.000Z', - 'key': 1422673200000, - 'doc_count': 136 - }, - { - 'key_as_string': '2015-01-31T04:00:00.000Z', - 'key': 1422676800000, - 'doc_count': 173 - }, - { - 'key_as_string': '2015-01-31T05:00:00.000Z', - 'key': 1422680400000, - 'doc_count': 370 - }, - { - 'key_as_string': '2015-01-31T06:00:00.000Z', - 'key': 1422684000000, - 'doc_count': 545 - }, - { - 'key_as_string': '2015-01-31T07:00:00.000Z', - 'key': 1422687600000, - 'doc_count': 845 - }, - { - 'key_as_string': '2015-01-31T08:00:00.000Z', - 'key': 1422691200000, - 'doc_count': 1070 - }, - { - 'key_as_string': '2015-01-31T09:00:00.000Z', - 'key': 1422694800000, - 'doc_count': 1419 - }, - { - 'key_as_string': '2015-01-31T10:00:00.000Z', - 'key': 1422698400000, - 'doc_count': 1725 - }, - { - 'key_as_string': '2015-01-31T11:00:00.000Z', - 'key': 1422702000000, - 'doc_count': 1801 - }, - { - 'key_as_string': '2015-01-31T12:00:00.000Z', - 'key': 1422705600000, - 'doc_count': 1823 - }, - { - 'key_as_string': '2015-01-31T13:00:00.000Z', - 'key': 1422709200000, - 'doc_count': 1657 - }, - { - 'key_as_string': '2015-01-31T14:00:00.000Z', - 'key': 1422712800000, - 'doc_count': 1454 - }, - { - 'key_as_string': '2015-01-31T15:00:00.000Z', - 'key': 1422716400000, - 'doc_count': 1131 - }, - { - 'key_as_string': '2015-01-31T16:00:00.000Z', - 'key': 1422720000000, - 'doc_count': 810 - }, - { - 'key_as_string': '2015-01-31T17:00:00.000Z', - 'key': 1422723600000, - 'doc_count': 583 - }, - { - 'key_as_string': '2015-01-31T18:00:00.000Z', - 'key': 1422727200000, - 'doc_count': 384 - }, - { - 'key_as_string': '2015-01-31T19:00:00.000Z', - 'key': 1422730800000, - 'doc_count': 165 - }, - { - 'key_as_string': '2015-01-31T20:00:00.000Z', - 'key': 1422734400000, - 'doc_count': 135 - }, - { - 'key_as_string': '2015-01-31T21:00:00.000Z', - 'key': 1422738000000, - 'doc_count': 72 - }, - { - 'key_as_string': '2015-01-31T22:00:00.000Z', - 'key': 1422741600000, - 'doc_count': 8 - } - ] - } +export default { + 'took': 35, + 'timed_out': false, + '_shards': { + 'total': 2, + 'successful': 2, + 'failed': 0 + }, + 'hits': { + 'total': 32899, + 'max_score': 0, + 'hits': [] + }, + 'aggregations': { + '1': { + 'buckets': [ + { + 'key_as_string': '2015-01-30T01:00:00.000Z', + 'key': 1422579600000, + 'doc_count': 18 + }, + { + 'key_as_string': '2015-01-30T02:00:00.000Z', + 'key': 1422583200000, + 'doc_count': 68 + }, + { + 'key_as_string': '2015-01-30T03:00:00.000Z', + 'key': 1422586800000, + 'doc_count': 146 + }, + { + 'key_as_string': '2015-01-30T04:00:00.000Z', + 'key': 1422590400000, + 'doc_count': 149 + }, + { + 'key_as_string': '2015-01-30T05:00:00.000Z', + 'key': 1422594000000, + 'doc_count': 363 + }, + { + 'key_as_string': '2015-01-30T06:00:00.000Z', + 'key': 1422597600000, + 'doc_count': 555 + }, + { + 'key_as_string': '2015-01-30T07:00:00.000Z', + 'key': 1422601200000, + 'doc_count': 878 + }, + { + 'key_as_string': '2015-01-30T08:00:00.000Z', + 'key': 1422604800000, + 'doc_count': 1133 + }, + { + 'key_as_string': '2015-01-30T09:00:00.000Z', + 'key': 1422608400000, + 'doc_count': 1438 + }, + { + 'key_as_string': '2015-01-30T10:00:00.000Z', + 'key': 1422612000000, + 'doc_count': 1719 + }, + { + 'key_as_string': '2015-01-30T11:00:00.000Z', + 'key': 1422615600000, + 'doc_count': 1813 + }, + { + 'key_as_string': '2015-01-30T12:00:00.000Z', + 'key': 1422619200000, + 'doc_count': 1790 + }, + { + 'key_as_string': '2015-01-30T13:00:00.000Z', + 'key': 1422622800000, + 'doc_count': 1582 + }, + { + 'key_as_string': '2015-01-30T14:00:00.000Z', + 'key': 1422626400000, + 'doc_count': 1439 + }, + { + 'key_as_string': '2015-01-30T15:00:00.000Z', + 'key': 1422630000000, + 'doc_count': 1154 + }, + { + 'key_as_string': '2015-01-30T16:00:00.000Z', + 'key': 1422633600000, + 'doc_count': 847 + }, + { + 'key_as_string': '2015-01-30T17:00:00.000Z', + 'key': 1422637200000, + 'doc_count': 588 + }, + { + 'key_as_string': '2015-01-30T18:00:00.000Z', + 'key': 1422640800000, + 'doc_count': 374 + }, + { + 'key_as_string': '2015-01-30T19:00:00.000Z', + 'key': 1422644400000, + 'doc_count': 152 + }, + { + 'key_as_string': '2015-01-30T20:00:00.000Z', + 'key': 1422648000000, + 'doc_count': 140 + }, + { + 'key_as_string': '2015-01-30T21:00:00.000Z', + 'key': 1422651600000, + 'doc_count': 73 + }, + { + 'key_as_string': '2015-01-30T22:00:00.000Z', + 'key': 1422655200000, + 'doc_count': 28 + }, + { + 'key_as_string': '2015-01-30T23:00:00.000Z', + 'key': 1422658800000, + 'doc_count': 9 + }, + { + 'key_as_string': '2015-01-31T00:00:00.000Z', + 'key': 1422662400000, + 'doc_count': 29 + }, + { + 'key_as_string': '2015-01-31T01:00:00.000Z', + 'key': 1422666000000, + 'doc_count': 38 + }, + { + 'key_as_string': '2015-01-31T02:00:00.000Z', + 'key': 1422669600000, + 'doc_count': 70 + }, + { + 'key_as_string': '2015-01-31T03:00:00.000Z', + 'key': 1422673200000, + 'doc_count': 136 + }, + { + 'key_as_string': '2015-01-31T04:00:00.000Z', + 'key': 1422676800000, + 'doc_count': 173 + }, + { + 'key_as_string': '2015-01-31T05:00:00.000Z', + 'key': 1422680400000, + 'doc_count': 370 + }, + { + 'key_as_string': '2015-01-31T06:00:00.000Z', + 'key': 1422684000000, + 'doc_count': 545 + }, + { + 'key_as_string': '2015-01-31T07:00:00.000Z', + 'key': 1422687600000, + 'doc_count': 845 + }, + { + 'key_as_string': '2015-01-31T08:00:00.000Z', + 'key': 1422691200000, + 'doc_count': 1070 + }, + { + 'key_as_string': '2015-01-31T09:00:00.000Z', + 'key': 1422694800000, + 'doc_count': 1419 + }, + { + 'key_as_string': '2015-01-31T10:00:00.000Z', + 'key': 1422698400000, + 'doc_count': 1725 + }, + { + 'key_as_string': '2015-01-31T11:00:00.000Z', + 'key': 1422702000000, + 'doc_count': 1801 + }, + { + 'key_as_string': '2015-01-31T12:00:00.000Z', + 'key': 1422705600000, + 'doc_count': 1823 + }, + { + 'key_as_string': '2015-01-31T13:00:00.000Z', + 'key': 1422709200000, + 'doc_count': 1657 + }, + { + 'key_as_string': '2015-01-31T14:00:00.000Z', + 'key': 1422712800000, + 'doc_count': 1454 + }, + { + 'key_as_string': '2015-01-31T15:00:00.000Z', + 'key': 1422716400000, + 'doc_count': 1131 + }, + { + 'key_as_string': '2015-01-31T16:00:00.000Z', + 'key': 1422720000000, + 'doc_count': 810 + }, + { + 'key_as_string': '2015-01-31T17:00:00.000Z', + 'key': 1422723600000, + 'doc_count': 583 + }, + { + 'key_as_string': '2015-01-31T18:00:00.000Z', + 'key': 1422727200000, + 'doc_count': 384 + }, + { + 'key_as_string': '2015-01-31T19:00:00.000Z', + 'key': 1422730800000, + 'doc_count': 165 + }, + { + 'key_as_string': '2015-01-31T20:00:00.000Z', + 'key': 1422734400000, + 'doc_count': 135 + }, + { + 'key_as_string': '2015-01-31T21:00:00.000Z', + 'key': 1422738000000, + 'doc_count': 72 + }, + { + 'key_as_string': '2015-01-31T22:00:00.000Z', + 'key': 1422741600000, + 'doc_count': 8 + } + ] } - }; -}); \ No newline at end of file + } +}; \ No newline at end of file diff --git a/src/ui/public/agg_response/hierarchical/_collect_branch.js b/src/ui/public/agg_response/hierarchical/_collect_branch.js index eccaed50402d0..a8588f31d58ef 100644 --- a/src/ui/public/agg_response/hierarchical/_collect_branch.js +++ b/src/ui/public/agg_response/hierarchical/_collect_branch.js @@ -1,37 +1,35 @@ -define(function () { - return function (leaf) { - // walk up the branch for each parent - function walk(item, memo) { - // record the the depth - let depth = item.depth - 1; +export default function (leaf) { + // walk up the branch for each parent + function walk(item, memo) { + // record the the depth + let depth = item.depth - 1; - // Using the aggConfig determine what the field name is. If the aggConfig - // doesn't exist (which means it's an _all agg) then use the level for - // the field name - const { aggConfig } = item; - let field = (aggConfig && aggConfig.getFieldDisplayName()) - || (aggConfig && aggConfig.label) - || ('level ' + item.depth); + // Using the aggConfig determine what the field name is. If the aggConfig + // doesn't exist (which means it's an _all agg) then use the level for + // the field name + const { aggConfig } = item; + let field = (aggConfig && aggConfig.getFieldDisplayName()) + || (aggConfig && aggConfig.label) + || ('level ' + item.depth); - // Add the row to the tooltipScope.rows - memo.unshift({ - aggConfig, - depth: depth, - field: field, - bucket: item.name, - metric: item.size, - item: item - }); + // Add the row to the tooltipScope.rows + memo.unshift({ + aggConfig, + depth: depth, + field: field, + bucket: item.name, + metric: item.size, + item: item + }); - // If the item has a parent and it's also a child then continue walking - // up the branch - if (item.parent && item.parent.parent) { - return walk(item.parent, memo); - } else { - return memo; - } + // If the item has a parent and it's also a child then continue walking + // up the branch + if (item.parent && item.parent.parent) { + return walk(item.parent, memo); + } else { + return memo; } + } - return walk(leaf, []); - }; -}); + return walk(leaf, []); +}; diff --git a/src/ui/public/agg_response/point_series/_init_x_axis.js b/src/ui/public/agg_response/point_series/_init_x_axis.js index 2a3584c3834f7..287bb3bdcaea4 100644 --- a/src/ui/public/agg_response/point_series/_init_x_axis.js +++ b/src/ui/public/agg_response/point_series/_init_x_axis.js @@ -1,17 +1,15 @@ -define(function () { - return function PointSeriesInitX() { - return function initXAxis(chart) { - let x = chart.aspects.x; - chart.xAxisFormatter = x.agg ? x.agg.fieldFormatter() : String; - chart.xAxisLabel = x.col.title; +export default function PointSeriesInitX() { + return function initXAxis(chart) { + let x = chart.aspects.x; + chart.xAxisFormatter = x.agg ? x.agg.fieldFormatter() : String; + chart.xAxisLabel = x.col.title; - if (!x.agg || !x.agg.type.ordered) return; + if (!x.agg || !x.agg.type.ordered) return; - chart.ordered = {}; - let xAggOutput = x.agg.write(); - if (xAggOutput.params.interval) { - chart.ordered.interval = xAggOutput.params.interval; - } - }; + chart.ordered = {}; + let xAggOutput = x.agg.write(); + if (xAggOutput.params.interval) { + chart.ordered.interval = xAggOutput.params.interval; + } }; -}); +}; diff --git a/src/ui/public/filter_bar/lib/map_script.js b/src/ui/public/filter_bar/lib/map_script.js index 0cbe74a6b1b35..9c829f78794d3 100644 --- a/src/ui/public/filter_bar/lib/map_script.js +++ b/src/ui/public/filter_bar/lib/map_script.js @@ -1,27 +1,25 @@ -define(function () { - return function mapScriptProvider(Promise, courier) { - return function (filter) { - let key; - let value; - let field; - if (filter.script) { - return courier - .indexPatterns - .get(filter.meta.index).then(function (indexPattern) { - key = filter.meta.field; - field = indexPattern.fields.byName[key]; +export default function mapScriptProvider(Promise, courier) { + return function (filter) { + let key; + let value; + let field; + if (filter.script) { + return courier + .indexPatterns + .get(filter.meta.index).then(function (indexPattern) { + key = filter.meta.field; + field = indexPattern.fields.byName[key]; - if (filter.meta.formattedValue) { - value = filter.meta.formattedValue; - } else { - value = filter.script.script.params.value; - value = field.format.convert(value); - } + if (filter.meta.formattedValue) { + value = filter.meta.formattedValue; + } else { + value = filter.script.script.params.value; + value = field.format.convert(value); + } - return { key: key, value: value }; - }); - } - return Promise.reject(filter); - }; + return { key: key, value: value }; + }); + } + return Promise.reject(filter); }; -}); +}; diff --git a/src/ui/public/utils/add_word_breaks.js b/src/ui/public/utils/add_word_breaks.js index 6f2454e93ebe4..eb346dae50afd 100644 --- a/src/ui/public/utils/add_word_breaks.js +++ b/src/ui/public/utils/add_word_breaks.js @@ -1,49 +1,47 @@ -define(function () { - return function addWordBreaks(text, minLineLength) { - text = text || ''; - let lineSize = 0; - let newText = ''; - let inHtmlTag = false; - let inHtmlChar = false; +export default function addWordBreaks(text, minLineLength) { + text = text || ''; + let lineSize = 0; + let newText = ''; + let inHtmlTag = false; + let inHtmlChar = false; - for (let i = 0, len = text.length; i < len; i++) { - let chr = text.charAt(i); - newText += chr; + for (let i = 0, len = text.length; i < len; i++) { + let chr = text.charAt(i); + newText += chr; - switch (chr) { - case ' ': - case ':': - case ',': - // natural line break, reset line size - lineSize = 0; - break; - case '<': - inHtmlTag = true; - break; - case '>': - inHtmlTag = false; - lineSize = 0; - break; - case '&': - inHtmlChar = true; - break; - case ';': - inHtmlChar = false; - lineSize = 0; - break; - default: - if (!inHtmlTag && !inHtmlChar) lineSize++; - break; - } - - if (lineSize > minLineLength) { - // continuous text is longer then we want, - // so break it up with a + switch (chr) { + case ' ': + case ':': + case ',': + // natural line break, reset line size + lineSize = 0; + break; + case '<': + inHtmlTag = true; + break; + case '>': + inHtmlTag = false; + lineSize = 0; + break; + case '&': + inHtmlChar = true; + break; + case ';': + inHtmlChar = false; lineSize = 0; - newText += ''; - } + break; + default: + if (!inHtmlTag && !inHtmlChar) lineSize++; + break; + } + + if (lineSize > minLineLength) { + // continuous text is longer then we want, + // so break it up with a + lineSize = 0; + newText += ''; } + } - return newText; - }; -}); + return newText; +}; diff --git a/src/ui/public/utils/es_bool.js b/src/ui/public/utils/es_bool.js index a580ffac72188..728d64957cfa6 100644 --- a/src/ui/public/utils/es_bool.js +++ b/src/ui/public/utils/es_bool.js @@ -1,22 +1,20 @@ -define(function () { - let map = { - 'false': false, - 'off': false, - 'no': false, - '0': false, - 'true': true, - 'on': true, - 'yes': true, - '1': true - }; +let map = { + 'false': false, + 'off': false, + 'no': false, + '0': false, + 'true': true, + 'on': true, + 'yes': true, + '1': true +}; - return function (str) { - let bool = map[String(str)]; +export default function (str) { + let bool = map[String(str)]; - if (typeof bool !== 'boolean') { - throw new TypeError('"' + str + '" does not map to an esBool'); - } + if (typeof bool !== 'boolean') { + throw new TypeError('"' + str + '" does not map to an esBool'); + } - return bool; - }; -}); + return bool; +}; diff --git a/src/ui/public/utils/ipv4_address.js b/src/ui/public/utils/ipv4_address.js index d8c396d02ab6b..7330a0f1cb13c 100644 --- a/src/ui/public/utils/ipv4_address.js +++ b/src/ui/public/utils/ipv4_address.js @@ -1,50 +1,48 @@ -define(function () { - let NUM_BYTES = 4; - let BYTE_SIZE = 256; +let NUM_BYTES = 4; +let BYTE_SIZE = 256; - function throwError(ipAddress) { - throw Error('Invalid IPv4 address: ' + ipAddress); - } +function throwError(ipAddress) { + throw Error('Invalid IPv4 address: ' + ipAddress); +} - function isIntegerInRange(integer, min, max) { - return !isNaN(integer) - && integer >= min - && integer < max - && integer % 1 === 0; - } +function isIntegerInRange(integer, min, max) { + return !isNaN(integer) + && integer >= min + && integer < max + && integer % 1 === 0; +} - function Ipv4Address(ipAddress) { - this.value = ipAddress; +function Ipv4Address(ipAddress) { + this.value = ipAddress; - if (typeof ipAddress === 'string') { - this.value = 0; + if (typeof ipAddress === 'string') { + this.value = 0; - let bytes = ipAddress.split('.'); - if (bytes.length !== NUM_BYTES) throwError(ipAddress); + let bytes = ipAddress.split('.'); + if (bytes.length !== NUM_BYTES) throwError(ipAddress); - for (let i = 0; i < bytes.length; i++) { - let byte = Number(bytes[i]); - if (!isIntegerInRange(byte, 0, BYTE_SIZE)) throwError(ipAddress); - this.value += Math.pow(BYTE_SIZE, NUM_BYTES - 1 - i) * byte; - } + for (let i = 0; i < bytes.length; i++) { + let byte = Number(bytes[i]); + if (!isIntegerInRange(byte, 0, BYTE_SIZE)) throwError(ipAddress); + this.value += Math.pow(BYTE_SIZE, NUM_BYTES - 1 - i) * byte; } - - if (!isIntegerInRange(this.value, 0, Math.pow(BYTE_SIZE, NUM_BYTES))) throwError(ipAddress); } - Ipv4Address.prototype.toString = function () { - let value = this.value; - let bytes = []; - for (let i = 0; i < NUM_BYTES; i++) { - bytes.unshift(value % 256); - value = Math.floor(value / 256); - } - return bytes.join('.'); - }; + if (!isIntegerInRange(this.value, 0, Math.pow(BYTE_SIZE, NUM_BYTES))) throwError(ipAddress); +} + +Ipv4Address.prototype.toString = function () { + let value = this.value; + let bytes = []; + for (let i = 0; i < NUM_BYTES; i++) { + bytes.unshift(value % 256); + value = Math.floor(value / 256); + } + return bytes.join('.'); +}; - Ipv4Address.prototype.valueOf = function () { - return this.value; - }; +Ipv4Address.prototype.valueOf = function () { + return this.value; +}; - return Ipv4Address; -}); +export default Ipv4Address; diff --git a/src/ui/public/utils/mapping_setup.js b/src/ui/public/utils/mapping_setup.js index fdca52ff7afc9..0b02d3e5a5788 100644 --- a/src/ui/public/utils/mapping_setup.js +++ b/src/ui/public/utils/mapping_setup.js @@ -1,110 +1,108 @@ import angular from 'angular'; import _ from 'lodash'; -define(function () { - return function MappingSetupService(kbnIndex, es) { - let mappingSetup = this; - let json = { - _serialize: function (val) { - if (val != null) return angular.toJson(val); - }, - _deserialize: function (val) { - if (val != null) return JSON.parse(val); - } - }; +export default function MappingSetupService(kbnIndex, es) { + let mappingSetup = this; - /** - * Use to create the mappings, but that should only happen one at a time - */ - let activeTypeCreations = {}; + let json = { + _serialize: function (val) { + if (val != null) return angular.toJson(val); + }, + _deserialize: function (val) { + if (val != null) return JSON.parse(val); + } + }; - /** - * Get the list of type's mapped in elasticsearch - * @return {[type]} [description] - */ - let getKnownKibanaTypes = _.once(function () { - return es.indices.getFieldMapping({ - // only concerned with types in this kibana index - index: kbnIndex, - // check all types - type: '*', - // limit the response to just the _source field for each index - fields: '_source' - }).then(function (resp) { - // kbnIndex is not sufficient here, if the kibana indexed is aliased we need to use - // the root index name as key - const index = _.keys(resp)[0]; - return _.keys(resp[index].mappings); - }); + /** + * Use to create the mappings, but that should only happen one at a time + */ + let activeTypeCreations = {}; + + /** + * Get the list of type's mapped in elasticsearch + * @return {[type]} [description] + */ + let getKnownKibanaTypes = _.once(function () { + return es.indices.getFieldMapping({ + // only concerned with types in this kibana index + index: kbnIndex, + // check all types + type: '*', + // limit the response to just the _source field for each index + fields: '_source' + }).then(function (resp) { + // kbnIndex is not sufficient here, if the kibana indexed is aliased we need to use + // the root index name as key + const index = _.keys(resp)[0]; + return _.keys(resp[index].mappings); }); + }); - mappingSetup.expandShorthand = function (sh) { - return _.mapValues(sh || {}, function (val, prop) { - // allow shortcuts for the field types, by just setting the value - // to the type name - if (typeof val === 'string') val = { type: val }; + mappingSetup.expandShorthand = function (sh) { + return _.mapValues(sh || {}, function (val, prop) { + // allow shortcuts for the field types, by just setting the value + // to the type name + if (typeof val === 'string') val = { type: val }; - if (val.type === 'json') { - val.type = 'string'; - val._serialize = json._serialize; - val._deserialize = json._deserialize; - } + if (val.type === 'json') { + val.type = 'string'; + val._serialize = json._serialize; + val._deserialize = json._deserialize; + } - return val; - }); - }; + return val; + }); + }; - mappingSetup.isDefined = function (type) { - return getKnownKibanaTypes() - .then(function (knownTypes) { - // if the type is in the knownTypes array already - return !!(~knownTypes.indexOf(type)); - }); - }; + mappingSetup.isDefined = function (type) { + return getKnownKibanaTypes() + .then(function (knownTypes) { + // if the type is in the knownTypes array already + return !!(~knownTypes.indexOf(type)); + }); + }; - mappingSetup.setup = function (type, mapping) { - // if there is already a creation running for this index type - if (activeTypeCreations[type]) { - // return a promise that will reexecute the setup once the - // current is complete. - return activeTypeCreations[type].then(function () { - return mappingSetup.setup(type, mapping); - }); - } + mappingSetup.setup = function (type, mapping) { + // if there is already a creation running for this index type + if (activeTypeCreations[type]) { + // return a promise that will reexecute the setup once the + // current is complete. + return activeTypeCreations[type].then(function () { + return mappingSetup.setup(type, mapping); + }); + } - let prom = getKnownKibanaTypes() - .then(function (knownTypes) { - // if the type is in the knownTypes array already - if (~knownTypes.indexOf(type)) return false; + let prom = getKnownKibanaTypes() + .then(function (knownTypes) { + // if the type is in the knownTypes array already + if (~knownTypes.indexOf(type)) return false; - // we need to create the mapping - let body = {}; - body[type] = { - properties: mapping - }; + // we need to create the mapping + let body = {}; + body[type] = { + properties: mapping + }; - return es.indices.putMapping({ - index: kbnIndex, - type: type, - body: body - }).then(function (resp) { - // add this type to the list of knownTypes - knownTypes.push(type); + return es.indices.putMapping({ + index: kbnIndex, + type: type, + body: body + }).then(function (resp) { + // add this type to the list of knownTypes + knownTypes.push(type); - // cast the response to "true", meaning - // the mapping exists - return true; - }); - }) - // wether this fails or not, remove it from the activeTypeCreations obj - // once complete - .finally(function () { - delete activeTypeCreations[type]; + // cast the response to "true", meaning + // the mapping exists + return true; }); + }) + // wether this fails or not, remove it from the activeTypeCreations obj + // once complete + .finally(function () { + delete activeTypeCreations[type]; + }); - activeTypeCreations[type] = prom; - return prom; - }; + activeTypeCreations[type] = prom; + return prom; }; - -}); +}; diff --git a/src/ui/public/vis/agg_config_result.js b/src/ui/public/vis/agg_config_result.js index 4df97b55477c6..2ed3d95becf2a 100644 --- a/src/ui/public/vis/agg_config_result.js +++ b/src/ui/public/vis/agg_config_result.js @@ -1,47 +1,45 @@ -define(function () { - let i = 0; +let i = 0; - function AggConfigResult(aggConfig, parent, value, key) { - this.key = key; - this.value = value; - this.aggConfig = aggConfig; - this.$parent = parent; - this.$order = ++i; +function AggConfigResult(aggConfig, parent, value, key) { + this.key = key; + this.value = value; + this.aggConfig = aggConfig; + this.$parent = parent; + this.$order = ++i; - if (aggConfig.schema.group === 'buckets') { - this.type = 'bucket'; - } else { - this.type = 'metric'; - } + if (aggConfig.schema.group === 'buckets') { + this.type = 'bucket'; + } else { + this.type = 'metric'; } +} - /** - * Returns an array of the aggConfigResult and parents up the branch - * @returns {array} Array of aggConfigResults - */ - AggConfigResult.prototype.getPath = function () { - return (function walk(result, path) { - path.unshift(result); - if (result.$parent) return walk(result.$parent, path); - return path; - }(this, [])); - }; +/** + * Returns an array of the aggConfigResult and parents up the branch + * @returns {array} Array of aggConfigResults + */ +AggConfigResult.prototype.getPath = function () { + return (function walk(result, path) { + path.unshift(result); + if (result.$parent) return walk(result.$parent, path); + return path; + }(this, [])); +}; - /** - * Returns an Elasticsearch filter that represents the result. - * @returns {object} Elasticsearch filter - */ - AggConfigResult.prototype.createFilter = function () { - return this.aggConfig.createFilter(this.key); - }; +/** + * Returns an Elasticsearch filter that represents the result. + * @returns {object} Elasticsearch filter + */ +AggConfigResult.prototype.createFilter = function () { + return this.aggConfig.createFilter(this.key); +}; - AggConfigResult.prototype.toString = function (contentType) { - return this.aggConfig.fieldFormatter(contentType)(this.value); - }; +AggConfigResult.prototype.toString = function (contentType) { + return this.aggConfig.fieldFormatter(contentType)(this.value); +}; - AggConfigResult.prototype.valueOf = function () { - return this.value; - }; +AggConfigResult.prototype.valueOf = function () { + return this.value; +}; - return AggConfigResult; -}); +export default AggConfigResult; diff --git a/src/ui/public/vislib/components/color/seed_colors.js b/src/ui/public/vislib/components/color/seed_colors.js index aae433fece914..fca693bcfdef8 100644 --- a/src/ui/public/vislib/components/color/seed_colors.js +++ b/src/ui/public/vislib/components/color/seed_colors.js @@ -1,20 +1,11 @@ -define(function () { - /* - * Using a random color generator presented awful colors and unpredictable color schemes. - * So we needed to come up with a color scheme of our own that creates consistent, pleasing color patterns. - * The order allows us to guarantee that 1st, 2nd, 3rd, etc values always get the same color. - * Returns an array of 72 colors. - */ - - return function SeedColorUtilService() { - return [ - '#6eadc1', - '#57c17b', - '#6f87d8', - '#663db8', - '#bc52bc', - '#9e3533', - '#daa05d' - ]; - }; -}); +export default function SeedColorUtilService() { + return [ + '#6eadc1', + '#57c17b', + '#6f87d8', + '#663db8', + '#bc52bc', + '#9e3533', + '#daa05d' + ]; +}; diff --git a/src/ui/public/vislib/components/labels/pie/return_pie_names.js b/src/ui/public/vislib/components/labels/pie/return_pie_names.js index bb69a9542c870..d319593361e60 100644 --- a/src/ui/public/vislib/components/labels/pie/return_pie_names.js +++ b/src/ui/public/vislib/components/labels/pie/return_pie_names.js @@ -1,19 +1,17 @@ -define(function () { - return function ReturnPieNames() { - return function returnNames(array, index, columns) { - const names = []; +export default function ReturnPieNames() { + return function returnNames(array, index, columns) { + const names = []; - array.forEach(function (obj) { - names.push({ key: obj.name, index: index }); + array.forEach(function (obj) { + names.push({ key: obj.name, index: index }); - if (obj.children) { - returnNames(obj.children, (index + 1), columns).forEach(function (namedObj) { - names.push(namedObj); - }); - } - }); + if (obj.children) { + returnNames(obj.children, (index + 1), columns).forEach(function (namedObj) { + names.push(namedObj); + }); + } + }); - return names; - }; + return names; }; -}); +}; diff --git a/src/ui/public/vislib/components/zero_injection/zero_filled_array.js b/src/ui/public/vislib/components/zero_injection/zero_filled_array.js index ceeb4afc0c2f1..2e86f01bef383 100644 --- a/src/ui/public/vislib/components/zero_injection/zero_filled_array.js +++ b/src/ui/public/vislib/components/zero_injection/zero_filled_array.js @@ -1,28 +1,27 @@ import _ from 'lodash'; -define(function () { - return function ZeroFilledArrayUtilService() { - /* - * Accepts an array of x axis values (strings or numbers). - * Returns a zero filled array. - */ +export default function ZeroFilledArrayUtilService() { - return function (arr) { - if (!_.isArray(arr)) { - throw new Error('ZeroFilledArrayUtilService expects an array of strings or numbers'); - } + /* + * Accepts an array of x axis values (strings or numbers). + * Returns a zero filled array. + */ - const zeroFilledArray = []; + return function (arr) { + if (!_.isArray(arr)) { + throw new Error('ZeroFilledArrayUtilService expects an array of strings or numbers'); + } - arr.forEach(function (val) { - zeroFilledArray.push({ - x: val, - xi: Infinity, - y: 0 - }); + const zeroFilledArray = []; + + arr.forEach(function (val) { + zeroFilledArray.push({ + x: val, + xi: Infinity, + y: 0 }); + }); - return zeroFilledArray; - }; + return zeroFilledArray; }; -}); +}; diff --git a/src/ui/public/vislib/lib/layout/splits/column_chart/chart_split.js b/src/ui/public/vislib/lib/layout/splits/column_chart/chart_split.js index f32fc7a3ce364..53223dfe04044 100644 --- a/src/ui/public/vislib/lib/layout/splits/column_chart/chart_split.js +++ b/src/ui/public/vislib/lib/layout/splits/column_chart/chart_split.js @@ -1,50 +1,49 @@ import d3 from 'd3'; -define(function () { - return function ChartSplitFactory() { - /* - * Adds div DOM elements to the `.chart-wrapper` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.chart` elements as row objects. - */ - return function split(selection) { - selection.each(function (data) { - const div = d3.select(this) - .attr('class', function () { - if (data.rows) { - return 'chart-wrapper-row'; - } else if (data.columns) { - return 'chart-wrapper-column'; - } else { - return 'chart-wrapper'; - } - }); - let divClass; +export default function ChartSplitFactory() { - const charts = div.selectAll('charts') - .append('div') - .data(function (d) { - if (d.rows) { - divClass = 'chart-row'; - return d.rows; - } else if (d.columns) { - divClass = 'chart-column'; - return d.columns; - } else { - divClass = 'chart'; - return [d]; - } - }) - .enter() - .append('div') - .attr('class', function () { - return divClass; - }); - - if (!data.series) { - charts.call(split); + /* + * Adds div DOM elements to the `.chart-wrapper` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.chart` elements as row objects. + */ + return function split(selection) { + selection.each(function (data) { + const div = d3.select(this) + .attr('class', function () { + if (data.rows) { + return 'chart-wrapper-row'; + } else if (data.columns) { + return 'chart-wrapper-column'; + } else { + return 'chart-wrapper'; } }); - }; + let divClass; + + const charts = div.selectAll('charts') + .append('div') + .data(function (d) { + if (d.rows) { + divClass = 'chart-row'; + return d.rows; + } else if (d.columns) { + divClass = 'chart-column'; + return d.columns; + } else { + divClass = 'chart'; + return [d]; + } + }) + .enter() + .append('div') + .attr('class', function () { + return divClass; + }); + + if (!data.series) { + charts.call(split); + } + }); }; -}); +}; diff --git a/src/ui/public/vislib/lib/layout/splits/column_chart/chart_title_split.js b/src/ui/public/vislib/lib/layout/splits/column_chart/chart_title_split.js index eaeb1947ef8ef..af1eac4eec368 100644 --- a/src/ui/public/vislib/lib/layout/splits/column_chart/chart_title_split.js +++ b/src/ui/public/vislib/lib/layout/splits/column_chart/chart_title_split.js @@ -1,41 +1,39 @@ import d3 from 'd3'; import $ from 'jquery'; -define(function () { - return function ChartTitleSplitFactory() { +export default function ChartTitleSplitFactory() { - /* - * Adds div DOM elements to either the `.y-axis-chart-title` element or the - * `.x-axis-chart-title` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.chart-title` elements as row objects. - * if not data.rows or data.columns, return no chart titles - */ - return function (selection) { - selection.each(function (data) { - const div = d3.select(this); - const parent = $(this).parents('.vis-wrapper'); + /* + * Adds div DOM elements to either the `.y-axis-chart-title` element or the + * `.x-axis-chart-title` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.chart-title` elements as row objects. + * if not data.rows or data.columns, return no chart titles + */ + return function (selection) { + selection.each(function (data) { + const div = d3.select(this); + const parent = $(this).parents('.vis-wrapper'); - if (!data.series) { - div.selectAll('.chart-title') - .data(function (d) { - return d.rows ? d.rows : d.columns; - }) - .enter() - .append('div') - .attr('class', 'chart-title'); + if (!data.series) { + div.selectAll('.chart-title') + .data(function (d) { + return d.rows ? d.rows : d.columns; + }) + .enter() + .append('div') + .attr('class', 'chart-title'); - if (data.rows) { - parent.find('.x-axis-chart-title').remove(); - } else { - parent.find('.y-axis-chart-title').remove(); - } - - return div; + if (data.rows) { + parent.find('.x-axis-chart-title').remove(); + } else { + parent.find('.y-axis-chart-title').remove(); } - return d3.select(this).remove(); - }); - }; + return div; + } + + return d3.select(this).remove(); + }); }; -}); +}; diff --git a/src/ui/public/vislib/lib/layout/splits/column_chart/x_axis_split.js b/src/ui/public/vislib/lib/layout/splits/column_chart/x_axis_split.js index 2d99d4bbd25bc..d2e5dc7b930ae 100644 --- a/src/ui/public/vislib/lib/layout/splits/column_chart/x_axis_split.js +++ b/src/ui/public/vislib/lib/layout/splits/column_chart/x_axis_split.js @@ -1,26 +1,25 @@ import d3 from 'd3'; -define(function () { - return function XAxisSplitFactory() { - /* - * Adds div DOM elements to the `.x-axis-div-wrapper` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.x-axis-div` elements as row objects. - */ +export default function XAxisSplitFactory() { - return function (selection) { - selection.each(function () { - const div = d3.select(this); + /* + * Adds div DOM elements to the `.x-axis-div-wrapper` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.x-axis-div` elements as row objects. + */ - div.selectAll('.x-axis-div') + return function (selection) { + selection.each(function () { + const div = d3.select(this); + + div.selectAll('.x-axis-div') + .append('div') + .data(function (d) { + return d.columns ? d.columns : [d]; + }) + .enter() .append('div') - .data(function (d) { - return d.columns ? d.columns : [d]; - }) - .enter() - .append('div') - .attr('class', 'x-axis-div'); - }); - }; + .attr('class', 'x-axis-div'); + }); }; -}); +}; diff --git a/src/ui/public/vislib/lib/layout/splits/column_chart/y_axis_split.js b/src/ui/public/vislib/lib/layout/splits/column_chart/y_axis_split.js index 93d8188073a18..90c9a50aed355 100644 --- a/src/ui/public/vislib/lib/layout/splits/column_chart/y_axis_split.js +++ b/src/ui/public/vislib/lib/layout/splits/column_chart/y_axis_split.js @@ -1,48 +1,47 @@ import d3 from 'd3'; -define(function () { - return function YAxisSplitFactory() { - /* - * Adds div DOM elements to the `.y-axis-div-wrapper` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.y-axis-div` elements as row objects. - */ +export default function YAxisSplitFactory() { - // render and get bounding box width - return function (selection, parent, opts) { - const yAxis = opts && opts.yAxis; + /* + * Adds div DOM elements to the `.y-axis-div-wrapper` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.y-axis-div` elements as row objects. + */ - selection.each(function () { - const div = d3.select(this); + // render and get bounding box width + return function (selection, parent, opts) { + const yAxis = opts && opts.yAxis; - div.call(setWidth, yAxis); + selection.each(function () { + const div = d3.select(this); - div.selectAll('.y-axis-div') + div.call(setWidth, yAxis); + + div.selectAll('.y-axis-div') + .append('div') + .data(function (d) { + return d.rows ? d.rows : [d]; + }) + .enter() .append('div') - .data(function (d) { - return d.rows ? d.rows : [d]; - }) - .enter() - .append('div') - .attr('class', 'y-axis-div'); - }); - }; - - function setWidth(el, yAxis) { - if (!yAxis) return; - - const padding = 5; - const height = parseInt(el.node().clientHeight, 10); - - // render svg and get the width of the bounding box - const svg = d3.select('body') - .append('svg') - .attr('style', 'position:absolute; top:-10000; left:-10000'); - const width = svg.append('g') - .call(yAxis.getYAxis(height)).node().getBBox().width + padding; - svg.remove(); - - el.style('width', (width + padding) + 'px'); - } + .attr('class', 'y-axis-div'); + }); }; -}); + + function setWidth(el, yAxis) { + if (!yAxis) return; + + const padding = 5; + const height = parseInt(el.node().clientHeight, 10); + + // render svg and get the width of the bounding box + const svg = d3.select('body') + .append('svg') + .attr('style', 'position:absolute; top:-10000; left:-10000'); + const width = svg.append('g') + .call(yAxis.getYAxis(height)).node().getBBox().width + padding; + svg.remove(); + + el.style('width', (width + padding) + 'px'); + } +}; diff --git a/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_split.js b/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_split.js index af58177503590..27441c525b842 100644 --- a/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_split.js +++ b/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_split.js @@ -1,51 +1,50 @@ import d3 from 'd3'; -define(function () { - return function ChartSplitFactory() { - /* - * Adds div DOM elements to the `.chart-wrapper` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.chart` elements as row objects. - */ +export default function ChartSplitFactory() { - return function split(selection) { - selection.each(function (data) { - const div = d3.select(this) - .attr('class', function () { - if (data.rows) { - return 'chart-wrapper-row'; - } else if (data.columns) { - return 'chart-wrapper-column'; - } else { - return 'chart-wrapper'; - } - }); - let divClass; + /* + * Adds div DOM elements to the `.chart-wrapper` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.chart` elements as row objects. + */ - const charts = div.selectAll('charts') - .append('div') - .data(function (d) { - if (d.rows) { - divClass = 'chart-row'; - return d.rows; - } else if (d.columns) { - divClass = 'chart-column'; - return d.columns; - } else { - divClass = 'chart'; - return [d]; - } - }) - .enter() - .append('div') - .attr('class', function () { - return divClass; - }); - - if (!data.slices) { - charts.call(split); + return function split(selection) { + selection.each(function (data) { + const div = d3.select(this) + .attr('class', function () { + if (data.rows) { + return 'chart-wrapper-row'; + } else if (data.columns) { + return 'chart-wrapper-column'; + } else { + return 'chart-wrapper'; } }); - }; + let divClass; + + const charts = div.selectAll('charts') + .append('div') + .data(function (d) { + if (d.rows) { + divClass = 'chart-row'; + return d.rows; + } else if (d.columns) { + divClass = 'chart-column'; + return d.columns; + } else { + divClass = 'chart'; + return [d]; + } + }) + .enter() + .append('div') + .attr('class', function () { + return divClass; + }); + + if (!data.slices) { + charts.call(split); + } + }); }; -}); +}; diff --git a/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js b/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js index d9c70f5ddff44..1b3a42f4a2cfe 100644 --- a/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js +++ b/src/ui/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js @@ -1,40 +1,39 @@ import d3 from 'd3'; -define(function () { - return function ChartTitleSplitFactory() { - /* - * Adds div DOM elements to either the `.y-axis-chart-title` element or the - * `.x-axis-chart-title` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.chart-title` elements as row objects. - * if not data.rows or data.columns, return no chart titles - */ +export default function ChartTitleSplitFactory() { - return function (selection, parent) { - selection.each(function (data) { - const div = d3.select(this); + /* + * Adds div DOM elements to either the `.y-axis-chart-title` element or the + * `.x-axis-chart-title` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.chart-title` elements as row objects. + * if not data.rows or data.columns, return no chart titles + */ - if (!data.slices) { - div.selectAll('.chart-title') - .append('div') - .data(function (d) { - return d.rows ? d.rows : d.columns; - }) - .enter() - .append('div') - .attr('class', 'chart-title'); + return function (selection, parent) { + selection.each(function (data) { + const div = d3.select(this); - if (data.rows) { - d3.select(parent).select('.x-axis-chart-title').remove(); - } else { - d3.select(parent).select('.y-axis-chart-title').remove(); - } + if (!data.slices) { + div.selectAll('.chart-title') + .append('div') + .data(function (d) { + return d.rows ? d.rows : d.columns; + }) + .enter() + .append('div') + .attr('class', 'chart-title'); - return div; + if (data.rows) { + d3.select(parent).select('.x-axis-chart-title').remove(); + } else { + d3.select(parent).select('.y-axis-chart-title').remove(); } - return d3.select(this).remove(); - }); - }; + return div; + } + + return d3.select(this).remove(); + }); }; -}); +}; diff --git a/src/ui/public/vislib/lib/layout/splits/tile_map/map_split.js b/src/ui/public/vislib/lib/layout/splits/tile_map/map_split.js index 710c77083927a..34aca75c0cf48 100644 --- a/src/ui/public/vislib/lib/layout/splits/tile_map/map_split.js +++ b/src/ui/public/vislib/lib/layout/splits/tile_map/map_split.js @@ -1,52 +1,51 @@ import d3 from 'd3'; -define(function () { - return function ChartSplitFactory() { - /* - * Adds div DOM elements to the `.chart-wrapper` element based on the data layout. - * For example, if the data has rows, it returns the same number of - * `.chart` elements as row objects. - */ - return function split(selection) { - selection.each(function (data) { - const div = d3.select(this) - .attr('class', function () { - // Determine the parent class - if (data.rows) { - return 'chart-wrapper-row'; - } else if (data.columns) { - return 'chart-wrapper-column'; - } else { - return 'chart-wrapper'; - } - }); - let divClass; +export default function ChartSplitFactory() { - const charts = div.selectAll('charts') - .append('div') - .data(function (d) { - // Determine the child class - if (d.rows) { - divClass = 'chart-row'; - return d.rows; - } else if (d.columns) { - divClass = 'chart-column'; - return d.columns; - } else { - divClass = 'chart'; - return [d]; - } - }) - .enter() - .append('div') - .attr('class', function () { - return divClass; - }); + /* + * Adds div DOM elements to the `.chart-wrapper` element based on the data layout. + * For example, if the data has rows, it returns the same number of + * `.chart` elements as row objects. + */ + return function split(selection) { + selection.each(function (data) { + const div = d3.select(this) + .attr('class', function () { + // Determine the parent class + if (data.rows) { + return 'chart-wrapper-row'; + } else if (data.columns) { + return 'chart-wrapper-column'; + } else { + return 'chart-wrapper'; + } + }); + let divClass; - if (!data.geoJson) { - charts.call(split); - } - }); - }; + const charts = div.selectAll('charts') + .append('div') + .data(function (d) { + // Determine the child class + if (d.rows) { + divClass = 'chart-row'; + return d.rows; + } else if (d.columns) { + divClass = 'chart-column'; + return d.columns; + } else { + divClass = 'chart'; + return [d]; + } + }) + .enter() + .append('div') + .attr('class', function () { + return divClass; + }); + + if (!data.geoJson) { + charts.call(split); + } + }); }; -}); +}; diff --git a/test/functional/index.js b/test/functional/index.js index 65bf202538814..30f9f8c0ae643 100644 --- a/test/functional/index.js +++ b/test/functional/index.js @@ -1,51 +1,49 @@ 'use strict'; // eslint-disable-line -define(function (require) { - require('intern/dojo/node!../support/env_setup'); - - const bdd = require('intern!bdd'); - const intern = require('intern'); - - global.__kibana__intern__ = { intern, bdd }; - - bdd.describe('kibana', function () { - let PageObjects; - let support; - - bdd.before(function () { - PageObjects.init(this.remote); - support.init(this.remote); - }); - const supportPages = [ - 'intern/dojo/node!../support/page_objects', - 'intern/dojo/node!../support' - ]; - - const requestedApps = process.argv.reduce((previous, arg) => { - const option = arg.split('='); - const key = option[0]; - const value = option[1]; - if (key === 'appSuites' && value) return value.split(','); - }); - - const apps = [ - 'intern/dojo/node!./apps/xpack', - 'intern/dojo/node!./apps/discover', - 'intern/dojo/node!./apps/management', - 'intern/dojo/node!./apps/visualize', - 'intern/dojo/node!./apps/console', - 'intern/dojo/node!./apps/dashboard', - 'intern/dojo/node!./status_page' - ].filter((suite) => { - if (!requestedApps) return true; - return requestedApps.reduce((previous, app) => { - return previous || ~suite.indexOf(app); - }, false); - }); - - require(supportPages.concat(apps), (loadedPageObjects, loadedSupport) => { - PageObjects = loadedPageObjects; - support = loadedSupport; - }); +require('intern/dojo/node!../support/env_setup'); + +const bdd = require('intern!bdd'); +const intern = require('intern'); + +global.__kibana__intern__ = { intern, bdd }; + +bdd.describe('kibana', function () { + let PageObjects; + let support; + + bdd.before(function () { + PageObjects.init(this.remote); + support.init(this.remote); + }); + const supportPages = [ + 'intern/dojo/node!../support/page_objects', + 'intern/dojo/node!../support' + ]; + + const requestedApps = process.argv.reduce((previous, arg) => { + const option = arg.split('='); + const key = option[0]; + const value = option[1]; + if (key === 'appSuites' && value) return value.split(','); + }); + + const apps = [ + 'intern/dojo/node!./apps/xpack', + 'intern/dojo/node!./apps/discover', + 'intern/dojo/node!./apps/management', + 'intern/dojo/node!./apps/visualize', + 'intern/dojo/node!./apps/console', + 'intern/dojo/node!./apps/dashboard', + 'intern/dojo/node!./status_page' + ].filter((suite) => { + if (!requestedApps) return true; + return requestedApps.reduce((previous, app) => { + return previous || ~suite.indexOf(app); + }, false); + }); + + require(supportPages.concat(apps), (loadedPageObjects, loadedSupport) => { + PageObjects = loadedPageObjects; + support = loadedSupport; }); }); diff --git a/test/intern.js b/test/intern.js index 095ae1cb8000f..39028b88107f4 100644 --- a/test/intern.js +++ b/test/intern.js @@ -1,22 +1,21 @@ -define(function (require) { - const serverConfig = require('intern/dojo/node!./server_config'); - return Object.assign({ - debug: true, - capabilities: { - 'idle-timeout': 99 - }, - environments: [{ - browserName: 'chrome' - }], - tunnelOptions: serverConfig.servers.webdriver, - functionalSuites: [ - 'test/functional/index' - ], +const serverConfig = require('intern/dojo/node!./server_config'); - excludeInstrumentation: /.*/, +export default Object.assign({ + debug: true, + capabilities: { + 'idle-timeout': 99 + }, + environments: [{ + browserName: 'chrome' + }], + tunnelOptions: serverConfig.servers.webdriver, + functionalSuites: [ + 'test/functional/index' + ], - defaultTimeout: 90000, - defaultTryTimeout: 40000, // tryForTime could include multiple 'find timeouts' - defaultFindTimeout: 10000 // this is how long we try to find elements on page - }, serverConfig); -}); + excludeInstrumentation: /.*/, + + defaultTimeout: 90000, + defaultTryTimeout: 40000, // tryForTime could include multiple 'find timeouts' + defaultFindTimeout: 10000 // this is how long we try to find elements on page +}, serverConfig); diff --git a/test/intern_visual_regression.js b/test/intern_visual_regression.js index 778e17f0cbf8b..30d2ec3804f29 100644 --- a/test/intern_visual_regression.js +++ b/test/intern_visual_regression.js @@ -1,24 +1,23 @@ -define(function (require) { - const serverConfig = require('intern/dojo/node!./server_config'); - return Object.assign({ - debug: true, - capabilities: { - 'selenium-version': '2.53.0', - // must match URL in tasks/config/downloadSelenium.js - 'idle-timeout': 99 - }, - environments: [{ - browserName: 'chrome' - }], - tunnelOptions: serverConfig.servers.webdriver, - functionalSuites: [ - 'test/visual_regression/index' - ], +const serverConfig = require('intern/dojo/node!./server_config'); - excludeInstrumentation: /.*/, +export default Object.assign({ + debug: true, + capabilities: { + 'selenium-version': '2.53.0', + // must match URL in tasks/config/downloadSelenium.js + 'idle-timeout': 99 + }, + environments: [{ + browserName: 'chrome' + }], + tunnelOptions: serverConfig.servers.webdriver, + functionalSuites: [ + 'test/visual_regression/index' + ], - defaultTimeout: 90000, - defaultTryTimeout: 40000, // tryForTime could include multiple 'find timeouts' - defaultFindTimeout: 10000 // this is how long we try to find elements on page - }, serverConfig); -}); + excludeInstrumentation: /.*/, + + defaultTimeout: 90000, + defaultTryTimeout: 40000, // tryForTime could include multiple 'find timeouts' + defaultFindTimeout: 10000 // this is how long we try to find elements on page +}, serverConfig); diff --git a/test/unit/api/ingest/_field_capabilities.js b/test/unit/api/ingest/_field_capabilities.js index e4be4a24b4930..e4f8b0f3eb62f 100644 --- a/test/unit/api/ingest/_field_capabilities.js +++ b/test/unit/api/ingest/_field_capabilities.js @@ -1,87 +1,85 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - return function (bdd, scenarioManager, request) { - bdd.describe('field_capabilities API', function postIngest() { +export default function (bdd, scenarioManager, request) { + bdd.describe('field_capabilities API', function postIngest() { - bdd.before(function () { + bdd.before(function () { + return scenarioManager.client.create({ + index: 'foo-1', + type: 'bar', + id: '1', + body: { + foo: 'bar' + } + }) + .then(function () { return scenarioManager.client.create({ - index: 'foo-1', + index: 'foo-2', type: 'bar', - id: '1', + id: '2', body: { - foo: 'bar' + baz: 'bar' } - }) - .then(function () { - return scenarioManager.client.create({ - index: 'foo-2', - type: 'bar', - id: '2', - body: { - baz: 'bar' - } - }); - }) - .then(function () { - return scenarioManager.client.indices.refresh({ - index: ['foo-1', 'foo-2'] - }); }); - }); - - bdd.after(function () { - return scenarioManager.reload('emptyKibana') - .then(function () { - scenarioManager.client.indices.delete({ - index: 'foo*' - }); + }) + .then(function () { + return scenarioManager.client.indices.refresh({ + index: ['foo-1', 'foo-2'] }); }); + }); - bdd.it('should return searchable/aggregatable flags for fields in the indices specified', function () { - return request.get('/kibana/foo-1/field_capabilities') - .expect(200) - .then(function (response) { - var fields = response.body.fields; - expect(fields.foo).to.eql({searchable: true, aggregatable: false}); - expect(fields['foo.keyword']).to.eql({searchable: true, aggregatable: true}); - expect(fields).to.not.have.property('baz'); + bdd.after(function () { + return scenarioManager.reload('emptyKibana') + .then(function () { + scenarioManager.client.indices.delete({ + index: 'foo*' }); }); + }); - bdd.it('should accept wildcards in the index name', function () { - return request.get('/kibana/foo-*/field_capabilities') - .expect(200) - .then(function (response) { - var fields = response.body.fields; - expect(fields.foo).to.eql({searchable: true, aggregatable: false}); - expect(fields.baz).to.eql({searchable: true, aggregatable: false}); - }); + bdd.it('should return searchable/aggregatable flags for fields in the indices specified', function () { + return request.get('/kibana/foo-1/field_capabilities') + .expect(200) + .then(function (response) { + var fields = response.body.fields; + expect(fields.foo).to.eql({searchable: true, aggregatable: false}); + expect(fields['foo.keyword']).to.eql({searchable: true, aggregatable: true}); + expect(fields).to.not.have.property('baz'); }); + }); - bdd.it('should accept comma delimited lists of indices', function () { - return request.get('/kibana/foo-1,foo-2/field_capabilities') - .expect(200) - .then(function (response) { - var fields = response.body.fields; - expect(fields.foo).to.eql({searchable: true, aggregatable: false}); - expect(fields.baz).to.eql({searchable: true, aggregatable: false}); - }); + bdd.it('should accept wildcards in the index name', function () { + return request.get('/kibana/foo-*/field_capabilities') + .expect(200) + .then(function (response) { + var fields = response.body.fields; + expect(fields.foo).to.eql({searchable: true, aggregatable: false}); + expect(fields.baz).to.eql({searchable: true, aggregatable: false}); }); + }); - bdd.it('should return 404 if a pattern matches no indices', function () { - return request.post('/kibana/doesnotexist-*/field_capabilities') - .expect(404); + bdd.it('should accept comma delimited lists of indices', function () { + return request.get('/kibana/foo-1,foo-2/field_capabilities') + .expect(200) + .then(function (response) { + var fields = response.body.fields; + expect(fields.foo).to.eql({searchable: true, aggregatable: false}); + expect(fields.baz).to.eql({searchable: true, aggregatable: false}); }); + }); - bdd.it('should return 404 if a concrete index does not exist', function () { - return request.post('/kibana/concrete/field_capabilities') - .expect(404); - }); + bdd.it('should return 404 if a pattern matches no indices', function () { + return request.post('/kibana/doesnotexist-*/field_capabilities') + .expect(404); + }); + bdd.it('should return 404 if a concrete index does not exist', function () { + return request.post('/kibana/concrete/field_capabilities') + .expect(404); }); - }; -}); + + }); +}; diff --git a/test/unit/api/ingest/_processors.js b/test/unit/api/ingest/_processors.js index ecb0c43d7b688..1fb94d2c2ac0f 100644 --- a/test/unit/api/ingest/_processors.js +++ b/test/unit/api/ingest/_processors.js @@ -1,19 +1,17 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - return function (bdd, scenarioManager, request) { - bdd.describe('processors', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('processors', () => { - bdd.it('should return 200 for a successful run', function () { - return request.get('/kibana/ingest/processors') - .expect(200) - .then((response) => { - expect(_.isArray(response.body)).to.be(true); - }); + bdd.it('should return 200 for a successful run', function () { + return request.get('/kibana/ingest/processors') + .expect(200) + .then((response) => { + expect(_.isArray(response.body)).to.be(true); }); - }); - }; -}); + + }); +}; diff --git a/test/unit/api/ingest/_simulate.js b/test/unit/api/ingest/_simulate.js index 7b8daf3c0fe7c..4110a5f4dd70a 100644 --- a/test/unit/api/ingest/_simulate.js +++ b/test/unit/api/ingest/_simulate.js @@ -1,157 +1,155 @@ -define(function (require) { - var Promise = require('bluebird'); - var createTestData = require('intern/dojo/node!../../../unit/api/ingest/data'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); - - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'set', - target_field: 'foo', - value: 'bar' - }], - input: {} - }; - - return function (bdd, scenarioManager, request) { - bdd.describe('simulate', function simulatePipeline() { - - bdd.it('should return 400 for an invalid payload', function invalidPayload() { - - return Promise.all([ - request.post('/kibana/ingest/simulate').expect(400), - - request.post('/kibana/ingest/simulate') - .send({}) - .expect(400), - - // requires at least one processor - request.post('/kibana/ingest/simulate') - .send({input: {}, processors: []}) - .expect(400), - - // All processors must have a processorId property and a typeId property - request.post('/kibana/ingest/simulate') - .send({input: {}, processors: [{}]}) - .expect(400), +var Promise = require('bluebird'); +var createTestData = require('intern/dojo/node!../../../unit/api/ingest/data'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); + +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'set', + target_field: 'foo', + value: 'bar' + }], + input: {} +}; + +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate', function simulatePipeline() { + + bdd.it('should return 400 for an invalid payload', function invalidPayload() { + + return Promise.all([ + request.post('/kibana/ingest/simulate').expect(400), + + request.post('/kibana/ingest/simulate') + .send({}) + .expect(400), + + // requires at least one processor + request.post('/kibana/ingest/simulate') + .send({input: {}, processors: []}) + .expect(400), + + // All processors must have a processorId property and a typeId property + request.post('/kibana/ingest/simulate') + .send({input: {}, processors: [{}]}) + .expect(400), + + request.post('/kibana/ingest/simulate') + .send({input: {}, processors: ['foo']}) + .expect(400), + + request.post('/kibana/ingest/simulate') + .send({input: {}, processors: 'foo'}) + .expect(400) + ]); + }); - request.post('/kibana/ingest/simulate') - .send({input: {}, processors: ['foo']}) - .expect(400), + bdd.it('should return 200 for a successful run', function () { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); + }); - request.post('/kibana/ingest/simulate') - .send({input: {}, processors: 'foo'}) - .expect(400) - ]); + bdd.describe('compilation errors', function simulatePipeline() { + const pipeline = { + input: { foo: '[message]' }, + processors: [ + { + processor_id: 'processor1', + type_id: 'set', + target_field: 'foo', + value: 'bar' + }, + { + processor_id: 'processor2', + type_id: 'gsub', + source_field: 'foo', + pattern: '[', + replacement: '<' + }, + { + processor_id: 'processor3', + type_id: 'set', + target_field: 'bar', + value: 'baz' + } + ] + }; + + bdd.it('should return a 200 for a compile error caused by a processor', function () { + request.post('/kibana/ingest/simulate') + .send(pipeline) + .expect(200) + .then((response) => { + expect(response.body[0].processor_id).to.be('processor2'); + expect(response.body[0].error.compile).to.be(true); + }); }); - bdd.it('should return 200 for a successful run', function () { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); + bdd.it('should only return a result for the processor that threw the error', function () { + request.post('/kibana/ingest/simulate') + .send(pipeline) + .expect(200) + .then((response) => { + expect(response.body[0].processor_id).to.be('processor2'); + expect(response.body[0].error.compile).to.be(true); + expect(response.body.length).to.be(1); + }); }); + }); - bdd.describe('compilation errors', function simulatePipeline() { - const pipeline = { - input: { foo: '[message]' }, - processors: [ - { - processor_id: 'processor1', - type_id: 'set', - target_field: 'foo', - value: 'bar' - }, - { - processor_id: 'processor2', - type_id: 'gsub', - source_field: 'foo', - pattern: '[', - replacement: '<' - }, - { - processor_id: 'processor3', - type_id: 'set', - target_field: 'bar', - value: 'baz' - } - ] - }; - - bdd.it('should return a 200 for a compile error caused by a processor', function () { + bdd.describe('data errors', function simulatePipeline() { + const pipeline = { + input: { foo: '[message]' }, + processors: [ + { + processor_id: 'processor1', + type_id: 'set', + target_field: 'foo', + value: 'bar' + }, + { + processor_id: 'processor2', + type_id: 'gsub', + source_field: '', //invalid source field + pattern: '\\[', + replacement: '<' + }, + { + processor_id: 'processor3', + type_id: 'set', + target_field: 'bar', + value: 'baz' + } + ] + }; + + bdd.it('should return 200 with non-compile error object for a processor with an invalid source_field', () => { + return Promise.all([ request.post('/kibana/ingest/simulate') .send(pipeline) .expect(200) .then((response) => { - expect(response.body[0].processor_id).to.be('processor2'); - expect(response.body[0].error.compile).to.be(true); - }); - }); + expect(response.body[0].error).to.be(undefined); + expect(response.body[1].error.compile).to.be(false); + expect(response.body[1].processor_id).to.be('processor2'); + }) + ]); + }); - bdd.it('should only return a result for the processor that threw the error', function () { + bdd.it('should return results up to and including the erroring processor', () => { + return Promise.all([ request.post('/kibana/ingest/simulate') .send(pipeline) .expect(200) .then((response) => { - expect(response.body[0].processor_id).to.be('processor2'); - expect(response.body[0].error.compile).to.be(true); - expect(response.body.length).to.be(1); - }); - }); - }); - - bdd.describe('data errors', function simulatePipeline() { - const pipeline = { - input: { foo: '[message]' }, - processors: [ - { - processor_id: 'processor1', - type_id: 'set', - target_field: 'foo', - value: 'bar' - }, - { - processor_id: 'processor2', - type_id: 'gsub', - source_field: '', //invalid source field - pattern: '\\[', - replacement: '<' - }, - { - processor_id: 'processor3', - type_id: 'set', - target_field: 'bar', - value: 'baz' - } - ] - }; - - bdd.it('should return 200 with non-compile error object for a processor with an invalid source_field', () => { - return Promise.all([ - request.post('/kibana/ingest/simulate') - .send(pipeline) - .expect(200) - .then((response) => { - expect(response.body[0].error).to.be(undefined); - expect(response.body[1].error.compile).to.be(false); - expect(response.body[1].processor_id).to.be('processor2'); - }) - ]); - }); - - bdd.it('should return results up to and including the erroring processor', () => { - return Promise.all([ - request.post('/kibana/ingest/simulate') - .send(pipeline) - .expect(200) - .then((response) => { - expect(response.body.length).to.be(2); - }) - ]); - }); - + expect(response.body.length).to.be(2); + }) + ]); }); }); - }; -}); + + }); +}; diff --git a/test/unit/api/ingest/index.js b/test/unit/api/ingest/index.js index b5f09ecc01aa6..ab4356c8328b8 100644 --- a/test/unit/api/ingest/index.js +++ b/test/unit/api/ingest/index.js @@ -1,31 +1,29 @@ -define(function (require) { - var bdd = require('intern!bdd'); - var serverConfig = require('intern/dojo/node!../../../server_config'); - var ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); - var request = require('intern/dojo/node!supertest-as-promised'); - var url = require('intern/dojo/node!url'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); - var simulate = require('./_simulate'); - var processors = require('./_processors'); - var processorTypes = require('./processors/index'); - var fieldCapabilities = require('./_field_capabilities'); +var bdd = require('intern!bdd'); +var serverConfig = require('intern/dojo/node!../../../server_config'); +var ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); +var request = require('intern/dojo/node!supertest-as-promised'); +var url = require('intern/dojo/node!url'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); +var simulate = require('./_simulate'); +var processors = require('./_processors'); +var processorTypes = require('./processors/index'); +var fieldCapabilities = require('./_field_capabilities'); - bdd.describe('ingest API', function () { - var scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); - request = request(url.format(serverConfig.servers.kibana) + '/api'); +bdd.describe('ingest API', function () { + var scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); + request = request(url.format(serverConfig.servers.kibana) + '/api'); - bdd.before(function () { - return scenarioManager.load('emptyKibana'); - }); - - bdd.after(function () { - return scenarioManager.unload('emptyKibana'); - }); + bdd.before(function () { + return scenarioManager.load('emptyKibana'); + }); - simulate(bdd, scenarioManager, request); - processors(bdd, scenarioManager, request); - processorTypes(bdd, scenarioManager, request); - fieldCapabilities(bdd, scenarioManager, request); + bdd.after(function () { + return scenarioManager.unload('emptyKibana'); }); + + simulate(bdd, scenarioManager, request); + processors(bdd, scenarioManager, request); + processorTypes(bdd, scenarioManager, request); + fieldCapabilities(bdd, scenarioManager, request); }); diff --git a/test/unit/api/ingest/processors/_append.js b/test/unit/api/ingest/processors/_append.js index 238cac6b9ee24..b82591e684409 100644 --- a/test/unit/api/ingest/processors/_append.js +++ b/test/unit/api/ingest/processors/_append.js @@ -1,67 +1,65 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'append', - target_field: 'foo', - values: [ 'value1', 'value2' ] - }], - input: {} - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'append', + target_field: 'foo', + values: [ 'value1', 'value2' ] + }], + input: {} +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - append processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - append processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // Append processor requires targetField property - request.post('/kibana/ingest/simulate') - .send({ - input: {}, - processors: [{ - processor_id: 'processor1', - type_id: 'append', - values: [ 'value1', 'value2' ], - target_field: 42 - }] - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output.foo).to.be.eql([ 'value1', 'value2' ]); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // Append processor requires targetField property + request.post('/kibana/ingest/simulate') .send({ + input: {}, processors: [{ - processorId: 'processor1', - typeId: 'append', - targetField: 'foo', - value: [ 'value1', 'value2' ] - }], - input: {} + processor_id: 'processor1', + type_id: 'append', + values: [ 'value1', 'value2' ], + target_field: 42 + }] }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output.foo).to.be.eql([ 'value1', 'value2' ]); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'append', + targetField: 'foo', + value: [ 'value1', 'value2' ] + }], + input: {} + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_convert.js b/test/unit/api/ingest/processors/_convert.js index 38a07d3507766..a186d3e0aef27 100644 --- a/test/unit/api/ingest/processors/_convert.js +++ b/test/unit/api/ingest/processors/_convert.js @@ -1,70 +1,68 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'convert', - source_field: 'foo', - target_field: 'foo', - type: 'auto' - }], - input: { foo: '1234' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'convert', + source_field: 'foo', + target_field: 'foo', + type: 'auto' + }], + input: { foo: '1234' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - convert processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - convert processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // Convert processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - input: {}, - processors: [{ - processor_id: 'processor1', - type_id: 'convert', - value: 'auto', - source_field: 42, - target_field: 'foo' - }] - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', function () { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output.foo).to.be(1234); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // Convert processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ + input: {}, processors: [{ - processorId: 'processor1', - typeId: 'convert', - sourceField: 'foo', - targetField: 'foo', - type: 'string' - }], - input: {} + processor_id: 'processor1', + type_id: 'convert', + value: 'auto', + source_field: 42, + target_field: 'foo' + }] }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', function () { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output.foo).to.be(1234); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'convert', + sourceField: 'foo', + targetField: 'foo', + type: 'string' + }], + input: {} + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_date.js b/test/unit/api/ingest/processors/_date.js index a3e018e4bd885..b011ec8c49dea 100644 --- a/test/unit/api/ingest/processors/_date.js +++ b/test/unit/api/ingest/processors/_date.js @@ -1,89 +1,87 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); - var moment = require('intern/dojo/node!moment'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); +var moment = require('intern/dojo/node!moment'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'date', - source_field: 'dob', - target_field: 'dob', - formats: ['Custom'], - timezone: 'Etc/UTC', - locale: 'ENGLISH', - custom_format: 'MM/dd/yyyy' - }], - input: { dob: '07/05/1979' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'date', + source_field: 'dob', + target_field: 'dob', + formats: ['Custom'], + timezone: 'Etc/UTC', + locale: 'ENGLISH', + custom_format: 'MM/dd/yyyy' + }], + input: { dob: '07/05/1979' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - date processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - date processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // Date processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - input: { dob: '07/05/1979' }, - processors: [{ - processor_id: 'processor1', - type_id: 'date', - source_field: 42, - target_field: 'dob', - formats: 'Custom', - timezone: 'Etc/UTC', - locale: 'ENGLISH', - custom_format: 'MM/dd/yyyy' - }] - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', function () { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output.dob).to.be('1979-07-05T00:00:00.000Z'); - }); - }); - - bdd.it('should return a date in ISO 8601 format', function () { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(moment(response.body[0].output.dob, moment.ISO_8601).isValid()).to.be(true); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // Date processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ + input: { dob: '07/05/1979' }, processors: [{ - processorId: 'processor1', - typeId: 'date', - sourceField: 'dob', - targetField: 'dob', - formats: ['Custom'], + processor_id: 'processor1', + type_id: 'date', + source_field: 42, + target_field: 'dob', + formats: 'Custom', timezone: 'Etc/UTC', locale: 'ENGLISH', - customFormat: 'MM/dd/yyyy' - }], - input: { dob: '07/05/1979' } + custom_format: 'MM/dd/yyyy' + }] }) - .expect(400); - }); + .expect(400) + ]); + }); + + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); + }); + + bdd.it('should return a simulated output with the correct result for the given processor', function () { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output.dob).to.be('1979-07-05T00:00:00.000Z'); + }); + }); + bdd.it('should return a date in ISO 8601 format', function () { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(moment(response.body[0].output.dob, moment.ISO_8601).isValid()).to.be(true); + }); }); - }; -}); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'date', + sourceField: 'dob', + targetField: 'dob', + formats: ['Custom'], + timezone: 'Etc/UTC', + locale: 'ENGLISH', + customFormat: 'MM/dd/yyyy' + }], + input: { dob: '07/05/1979' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_geoip.js b/test/unit/api/ingest/processors/_geoip.js index 452c3e5d8416c..4a610af00597d 100644 --- a/test/unit/api/ingest/processors/_geoip.js +++ b/test/unit/api/ingest/processors/_geoip.js @@ -1,71 +1,69 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'geoip', - source_field: 'ip', - target_field: 'geoip' - }], - input: { ip: '74.125.21.103' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'geoip', + source_field: 'ip', + target_field: 'geoip' + }], + input: { ip: '74.125.21.103' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - geoip processor', () => { - //TODO: These tests can be re-added when we address - // installing plugins for integration tests - // https://github.com/elastic/kibana/issues/6852 +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - geoip processor', () => { +//TODO: These tests can be re-added when we address +// installing plugins for integration tests +// https://github.com/elastic/kibana/issues/6852 - // bdd.it('should return 400 for an invalid payload', () => { - // return Promise.all([ - // // Geo IP processor requires source_field property - // request.post('/kibana/ingest/simulate') - // .send({ - // input: { ip: '74.125.21.103' }, - // processors: [{ - // processor_id: 'processor1', - // type_id: 'geoip', - // source_field: 42, - // target_field: 'geoip' - // }] - // }) - // .expect(400) - // ]); - // }); +// bdd.it('should return 400 for an invalid payload', () => { +// return Promise.all([ +// // Geo IP processor requires source_field property +// request.post('/kibana/ingest/simulate') +// .send({ +// input: { ip: '74.125.21.103' }, +// processors: [{ +// processor_id: 'processor1', +// type_id: 'geoip', +// source_field: 42, +// target_field: 'geoip' +// }] +// }) +// .expect(400) +// ]); +// }); - // bdd.it('should return 200 for a valid simulate request', () => { - // return request.post('/kibana/ingest/simulate') - // .send(testPipeline) - // .expect(200); - // }); +// bdd.it('should return 200 for a valid simulate request', () => { +// return request.post('/kibana/ingest/simulate') +// .send(testPipeline) +// .expect(200); +// }); - // bdd.it('should return a simulated output with the correct result for the given processor', () => { - // return request.post('/kibana/ingest/simulate') - // .send(testPipeline) - // .expect(200) - // .then(function (response) { - // expect(response.body[0].output.geoip.city_name).to.be('Mountain View'); - // }); - // }); +// bdd.it('should return a simulated output with the correct result for the given processor', () => { +// return request.post('/kibana/ingest/simulate') +// .send(testPipeline) +// .expect(200) +// .then(function (response) { +// expect(response.body[0].output.geoip.city_name).to.be('Mountain View'); +// }); +// }); - // bdd.it('should enforce snake case', () => { - // return request.post('/kibana/ingest/simulate') - // .send({ - // processors: [{ - // processorId: 'processor1', - // typeId: 'geoip', - // sourceField: 'ip', - // targetField: 'geoip' - // }], - // input: { ip: '74.125.21.103' } - // }) - // .expect(400); - // }); +// bdd.it('should enforce snake case', () => { +// return request.post('/kibana/ingest/simulate') +// .send({ +// processors: [{ +// processorId: 'processor1', +// typeId: 'geoip', +// sourceField: 'ip', +// targetField: 'geoip' +// }], +// input: { ip: '74.125.21.103' } +// }) +// .expect(400); +// }); - }); - }; -}); + }); +}; diff --git a/test/unit/api/ingest/processors/_grok.js b/test/unit/api/ingest/processors/_grok.js index b1ee7d4e2de25..7604b37785236 100644 --- a/test/unit/api/ingest/processors/_grok.js +++ b/test/unit/api/ingest/processors/_grok.js @@ -1,72 +1,70 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'grok', - source_field: 'foo', - pattern: '%{GREEDYDATA:bar} - %{GREEDYDATA:baz}' - }], - input: { foo: 'value1 - value2' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'grok', + source_field: 'foo', + pattern: '%{GREEDYDATA:bar} - %{GREEDYDATA:baz}' + }], + input: { foo: 'value1 - value2' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - grok processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - grok processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // Grok processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - input: {}, - processors: [{ - processor_id: 'processor1', - type_id: 'grok', - source_field: 123, - pattern: '%{GREEDYDATA:bar} - %{GREEDYDATA:baz}' - }], - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', function () { - const expected = { - foo: 'value1 - value2', - bar: 'value1', - baz: 'value2' - }; - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output).to.eql(expected); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // Grok processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ + input: {}, processors: [{ - processorId: 'processor1', - typeId: 'grok', - sourceField: 'foo', + processor_id: 'processor1', + type_id: 'grok', + source_field: 123, pattern: '%{GREEDYDATA:bar} - %{GREEDYDATA:baz}' }], - input: { foo: 'value1 - value2' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', function () { + const expected = { + foo: 'value1 - value2', + bar: 'value1', + baz: 'value2' + }; + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output).to.eql(expected); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'grok', + sourceField: 'foo', + pattern: '%{GREEDYDATA:bar} - %{GREEDYDATA:baz}' + }], + input: { foo: 'value1 - value2' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_gsub.js b/test/unit/api/ingest/processors/_gsub.js index 2d97067a911f1..8038fba513d84 100644 --- a/test/unit/api/ingest/processors/_gsub.js +++ b/test/unit/api/ingest/processors/_gsub.js @@ -1,70 +1,68 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'gsub', - source_field: 'foo', - pattern: 'bar', - replacement: 'baz' - }], - input: { foo: 'bar' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'gsub', + source_field: 'foo', + pattern: 'bar', + replacement: 'baz' + }], + input: { foo: 'bar' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - gsub processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - gsub processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // GSub processor requires targetField property - request.post('/kibana/ingest/simulate') - .send({ - input: { foo: 'bar' }, - processors: [{ - processor_id: 'processor1', - type_id: 'gsub', - source_field: 42, - pattern: 'bar', - replacement: 'baz' - }] - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then((response) => { - expect(response.body[0].output.foo).to.be.equal('baz'); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // GSub processor requires targetField property + request.post('/kibana/ingest/simulate') .send({ + input: { foo: 'bar' }, processors: [{ - processorId: 'processor1', - typeId: 'gsub', - sourceField: 'foo', + processor_id: 'processor1', + type_id: 'gsub', + source_field: 42, pattern: 'bar', replacement: 'baz' - }], - input: { foo: 'bar' } + }] }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then((response) => { + expect(response.body[0].output.foo).to.be.equal('baz'); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'gsub', + sourceField: 'foo', + pattern: 'bar', + replacement: 'baz' + }], + input: { foo: 'bar' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_join.js b/test/unit/api/ingest/processors/_join.js index 7e98650fc47c1..c82353c8bbbd2 100644 --- a/test/unit/api/ingest/processors/_join.js +++ b/test/unit/api/ingest/processors/_join.js @@ -1,67 +1,65 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'join', - source_field: 'foo', - separator: ' ' - }], - input: { foo: ['value1', 'value2'] } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'join', + source_field: 'foo', + separator: ' ' + }], + input: { foo: ['value1', 'value2'] } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - join processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - join processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'join', - source_field: 1234, - separator: ' ' - }], - input: { foo: ['value1', 'value2'] } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', function () { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output.foo).to.be('value1 value2'); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'join', - sourceField: 'foo', + processor_id: 'processor1', + type_id: 'join', + source_field: 1234, separator: ' ' }], input: { foo: ['value1', 'value2'] } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', function () { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output.foo).to.be('value1 value2'); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'join', + sourceField: 'foo', + separator: ' ' + }], + input: { foo: ['value1', 'value2'] } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_lowercase.js b/test/unit/api/ingest/processors/_lowercase.js index 747dfb003b6c6..c3809d03746f7 100644 --- a/test/unit/api/ingest/processors/_lowercase.js +++ b/test/unit/api/ingest/processors/_lowercase.js @@ -1,64 +1,62 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'lowercase', - source_field: 'foo' - }], - input: { foo: 'I am Mixed Case' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'lowercase', + source_field: 'foo' + }], + input: { foo: 'I am Mixed Case' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - lowercase processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - lowercase processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'lowercase', - source_field: 1234 - }], - input: { foo: 'I am Mixed Case' } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output.foo).to.be('i am mixed case'); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'lowercase', - sourceField: 'foo' + processor_id: 'processor1', + type_id: 'lowercase', + source_field: 1234 }], input: { foo: 'I am Mixed Case' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output.foo).to.be('i am mixed case'); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'lowercase', + sourceField: 'foo' + }], + input: { foo: 'I am Mixed Case' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_remove.js b/test/unit/api/ingest/processors/_remove.js index f454b79ff936b..fa37e13f9e2ca 100644 --- a/test/unit/api/ingest/processors/_remove.js +++ b/test/unit/api/ingest/processors/_remove.js @@ -1,64 +1,62 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'remove', - source_field: 'foo' - }], - input: { foo: 'value1', bar: 'value2' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'remove', + source_field: 'foo' + }], + input: { foo: 'value1', bar: 'value2' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - remove processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - remove processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'remove', - source_field: 1234 - }], - input: { foo: 'value1', bar: 'value2' } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output).to.eql({ bar: 'value2' }); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'remove', - sourceField: 'foo' + processor_id: 'processor1', + type_id: 'remove', + source_field: 1234 }], input: { foo: 'value1', bar: 'value2' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output).to.eql({ bar: 'value2' }); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'remove', + sourceField: 'foo' + }], + input: { foo: 'value1', bar: 'value2' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_rename.js b/test/unit/api/ingest/processors/_rename.js index 3370ba6f48b45..145021411a770 100644 --- a/test/unit/api/ingest/processors/_rename.js +++ b/test/unit/api/ingest/processors/_rename.js @@ -1,67 +1,65 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'rename', - source_field: 'foo', - target_field: 'bar' - }], - input: { foo: 'value1' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'rename', + source_field: 'foo', + target_field: 'bar' + }], + input: { foo: 'value1' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - rename processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - rename processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'rename', - source_field: 1234, - target_field: 'bar' - }], - input: { foo: 'value1' } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output).to.eql({ bar: 'value1' }); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'rename', - sourceField: 'foo', - targetField: 'bar' + processor_id: 'processor1', + type_id: 'rename', + source_field: 1234, + target_field: 'bar' }], input: { foo: 'value1' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output).to.eql({ bar: 'value1' }); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'rename', + sourceField: 'foo', + targetField: 'bar' + }], + input: { foo: 'value1' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_set.js b/test/unit/api/ingest/processors/_set.js index 395a29a80d5b2..0894bdbbfc3ae 100644 --- a/test/unit/api/ingest/processors/_set.js +++ b/test/unit/api/ingest/processors/_set.js @@ -1,67 +1,65 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'set', - target_field: 'foo', - value: 'bar' - }], - input: {} - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'set', + target_field: 'foo', + value: 'bar' + }], + input: {} +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - set processor', function simulatePipeline() { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - set processor', function simulatePipeline() { - bdd.it('should return 400 for an invalid payload', function invalidPayload() { - return Promise.all([ - // Set processor requires targetField property - request.post('/kibana/ingest/simulate') - .send({ - input: {}, - processors: [{ - processor_id: 'processor1', - type_id: 'set', - value: 'bar', - target_field: 42 - }] - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', function validSetSimulate() { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', function () { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output.foo).to.be.equal('bar'); - }); - }); - - bdd.it('should enforce snake case', function setSimulateSnakeCase() { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', function invalidPayload() { + return Promise.all([ + // Set processor requires targetField property + request.post('/kibana/ingest/simulate') .send({ + input: {}, processors: [{ - processorId: 'processor1', - typeId: 'set', - targetField: 'foo', - value: 'bar' - }], - input: {} + processor_id: 'processor1', + type_id: 'set', + value: 'bar', + target_field: 42 + }] }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', function validSetSimulate() { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', function () { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output.foo).to.be.equal('bar'); + }); + }); + + bdd.it('should enforce snake case', function setSimulateSnakeCase() { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'set', + targetField: 'foo', + value: 'bar' + }], + input: {} + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_split.js b/test/unit/api/ingest/processors/_split.js index 9e6900b0f822e..98b1c112cc9a6 100644 --- a/test/unit/api/ingest/processors/_split.js +++ b/test/unit/api/ingest/processors/_split.js @@ -1,67 +1,65 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'split', - source_field: 'foo', - separator: ',' - }], - input: { foo: 'foo,bar,baz' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'split', + source_field: 'foo', + separator: ',' + }], + input: { foo: 'foo,bar,baz' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - split processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - split processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'split', - source_field: 1234, - separator: ',' - }], - input: { foo: 'foo,bar,baz' } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output).to.eql({ foo: ['foo', 'bar', 'baz'] }); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'split', - sourceField: 'foo', + processor_id: 'processor1', + type_id: 'split', + source_field: 1234, separator: ',' }], input: { foo: 'foo,bar,baz' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output).to.eql({ foo: ['foo', 'bar', 'baz'] }); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'split', + sourceField: 'foo', + separator: ',' + }], + input: { foo: 'foo,bar,baz' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_trim.js b/test/unit/api/ingest/processors/_trim.js index 1f08d5c1eb167..817233f1a2022 100644 --- a/test/unit/api/ingest/processors/_trim.js +++ b/test/unit/api/ingest/processors/_trim.js @@ -1,64 +1,62 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'trim', - source_field: 'foo' - }], - input: { foo: ' bar baz ' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'trim', + source_field: 'foo' + }], + input: { foo: ' bar baz ' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - trim processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - trim processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'trim', - source_field: 1234 - }], - input: { foo: ' bar baz ' } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output).to.eql({ foo: 'bar baz' }); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'trim', - sourceField: 'foo' + processor_id: 'processor1', + type_id: 'trim', + source_field: 1234 }], input: { foo: ' bar baz ' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output).to.eql({ foo: 'bar baz' }); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'trim', + sourceField: 'foo' + }], + input: { foo: ' bar baz ' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/_uppercase.js b/test/unit/api/ingest/processors/_uppercase.js index c2cd5cf1b7256..de0f4091015de 100644 --- a/test/unit/api/ingest/processors/_uppercase.js +++ b/test/unit/api/ingest/processors/_uppercase.js @@ -1,64 +1,62 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - const testPipeline = { - processors: [{ - processor_id: 'processor1', - type_id: 'uppercase', - source_field: 'foo' - }], - input: { foo: 'bar baz' } - }; +const testPipeline = { + processors: [{ + processor_id: 'processor1', + type_id: 'uppercase', + source_field: 'foo' + }], + input: { foo: 'bar baz' } +}; - return function (bdd, scenarioManager, request) { - bdd.describe('simulate - uppercase processor', () => { +export default function (bdd, scenarioManager, request) { + bdd.describe('simulate - uppercase processor', () => { - bdd.it('should return 400 for an invalid payload', () => { - return Promise.all([ - // processor requires source_field property - request.post('/kibana/ingest/simulate') - .send({ - processors: [{ - processor_id: 'processor1', - type_id: 'uppercase', - source_field: 1234 - }], - input: { foo: 'bar baz' } - }) - .expect(400) - ]); - }); - - bdd.it('should return 200 for a valid simulate request', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200); - }); - - bdd.it('should return a simulated output with the correct result for the given processor', () => { - return request.post('/kibana/ingest/simulate') - .send(testPipeline) - .expect(200) - .then(function (response) { - expect(response.body[0].output).to.eql({ foo: 'BAR BAZ' }); - }); - }); - - bdd.it('should enforce snake case', () => { - return request.post('/kibana/ingest/simulate') + bdd.it('should return 400 for an invalid payload', () => { + return Promise.all([ + // processor requires source_field property + request.post('/kibana/ingest/simulate') .send({ processors: [{ - processorId: 'processor1', - typeId: 'uppercase', - sourceField: 'foo' + processor_id: 'processor1', + type_id: 'uppercase', + source_field: 1234 }], input: { foo: 'bar baz' } }) - .expect(400); - }); + .expect(400) + ]); + }); + bdd.it('should return 200 for a valid simulate request', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200); }); - }; -}); + + bdd.it('should return a simulated output with the correct result for the given processor', () => { + return request.post('/kibana/ingest/simulate') + .send(testPipeline) + .expect(200) + .then(function (response) { + expect(response.body[0].output).to.eql({ foo: 'BAR BAZ' }); + }); + }); + + bdd.it('should enforce snake case', () => { + return request.post('/kibana/ingest/simulate') + .send({ + processors: [{ + processorId: 'processor1', + typeId: 'uppercase', + sourceField: 'foo' + }], + input: { foo: 'bar baz' } + }) + .expect(400); + }); + + }); +}; diff --git a/test/unit/api/ingest/processors/index.js b/test/unit/api/ingest/processors/index.js index 3420996767864..9c0df6658d2fb 100644 --- a/test/unit/api/ingest/processors/index.js +++ b/test/unit/api/ingest/processors/index.js @@ -1,34 +1,31 @@ -define(function (require) { - var append = require('./_append'); - var convert = require('./_convert'); - var date = require('./_date'); - var geoip = require('./_geoip'); - var grok = require('./_grok'); - var gsub = require('./_gsub'); - var join = require('./_join'); - var lowercase = require('./_lowercase'); - var remove = require('./_remove'); - var rename = require('./_rename'); - var set = require('./_set'); - var split = require('./_split'); - var trim = require('./_trim'); - var uppercase = require('./_uppercase'); +var append = require('./_append'); +var convert = require('./_convert'); +var date = require('./_date'); +var geoip = require('./_geoip'); +var grok = require('./_grok'); +var gsub = require('./_gsub'); +var join = require('./_join'); +var lowercase = require('./_lowercase'); +var remove = require('./_remove'); +var rename = require('./_rename'); +var set = require('./_set'); +var split = require('./_split'); +var trim = require('./_trim'); +var uppercase = require('./_uppercase'); - return function processors(bdd, scenarioManager, request) { - append(bdd, scenarioManager, request); - convert(bdd, scenarioManager, request); - date(bdd, scenarioManager, request); - geoip(bdd, scenarioManager, request); - grok(bdd, scenarioManager, request); - gsub(bdd, scenarioManager, request); - join(bdd, scenarioManager, request); - lowercase(bdd, scenarioManager, request); - remove(bdd, scenarioManager, request); - rename(bdd, scenarioManager, request); - set(bdd, scenarioManager, request); - split(bdd, scenarioManager, request); - trim(bdd, scenarioManager, request); - uppercase(bdd, scenarioManager, request); - }; - -}); +export default function processors(bdd, scenarioManager, request) { + append(bdd, scenarioManager, request); + convert(bdd, scenarioManager, request); + date(bdd, scenarioManager, request); + geoip(bdd, scenarioManager, request); + grok(bdd, scenarioManager, request); + gsub(bdd, scenarioManager, request); + join(bdd, scenarioManager, request); + lowercase(bdd, scenarioManager, request); + remove(bdd, scenarioManager, request); + rename(bdd, scenarioManager, request); + set(bdd, scenarioManager, request); + split(bdd, scenarioManager, request); + trim(bdd, scenarioManager, request); + uppercase(bdd, scenarioManager, request); +}; diff --git a/test/unit/api/scripts/_languages.js b/test/unit/api/scripts/_languages.js index 9f9afa19926eb..837775e424ce2 100644 --- a/test/unit/api/scripts/_languages.js +++ b/test/unit/api/scripts/_languages.js @@ -1,27 +1,25 @@ -define(function (require) { - var expect = require('intern/dojo/node!expect.js'); +var expect = require('intern/dojo/node!expect.js'); - return function (bdd, request) { - bdd.describe('Languages API', function getLanguages() { +export default function (bdd, request) { + bdd.describe('Languages API', function getLanguages() { - bdd.it('should return 200 with an array of languages', function () { - return request.get('/kibana/scripts/languages') - .expect(200) - .then(function (response) { - expect(response.body).to.be.an('array'); - }); + bdd.it('should return 200 with an array of languages', function () { + return request.get('/kibana/scripts/languages') + .expect(200) + .then(function (response) { + expect(response.body).to.be.an('array'); }); + }); - bdd.it('should only return langs enabled for inline scripting', function () { - return request.get('/kibana/scripts/languages') - .expect(200) - .then(function (response) { - expect(response.body).to.contain('expression'); - expect(response.body).to.contain('painless'); + bdd.it('should only return langs enabled for inline scripting', function () { + return request.get('/kibana/scripts/languages') + .expect(200) + .then(function (response) { + expect(response.body).to.contain('expression'); + expect(response.body).to.contain('painless'); - expect(response.body).to.not.contain('groovy'); - }); + expect(response.body).to.not.contain('groovy'); }); }); - }; -}); + }); +}; diff --git a/test/unit/api/scripts/index.js b/test/unit/api/scripts/index.js index 7b147eec59bb7..5963e4efdb1db 100644 --- a/test/unit/api/scripts/index.js +++ b/test/unit/api/scripts/index.js @@ -1,13 +1,11 @@ -define(function (require) { - var bdd = require('intern!bdd'); - var serverConfig = require('intern/dojo/node!../../../server_config'); - var request = require('intern/dojo/node!supertest-as-promised'); - var url = require('intern/dojo/node!url'); - var languages = require('./_languages'); +var bdd = require('intern!bdd'); +var serverConfig = require('intern/dojo/node!../../../server_config'); +var request = require('intern/dojo/node!supertest-as-promised'); +var url = require('intern/dojo/node!url'); +var languages = require('./_languages'); - bdd.describe('scripts API', function () { - request = request(url.format(serverConfig.servers.kibana) + '/api'); +bdd.describe('scripts API', function () { + request = request(url.format(serverConfig.servers.kibana) + '/api'); - languages(bdd, request); - }); + languages(bdd, request); }); diff --git a/test/unit/api/search/_count.js b/test/unit/api/search/_count.js index 239a936cfd1ed..52e7debe1594a 100644 --- a/test/unit/api/search/_count.js +++ b/test/unit/api/search/_count.js @@ -1,72 +1,70 @@ -define(function (require) { - var Promise = require('bluebird'); - var _ = require('intern/dojo/node!lodash'); - var expect = require('intern/dojo/node!expect.js'); +var Promise = require('bluebird'); +var _ = require('intern/dojo/node!lodash'); +var expect = require('intern/dojo/node!expect.js'); - return function (bdd, scenarioManager, request) { - bdd.describe('Count API', function postIngest() { +export default function (bdd, scenarioManager, request) { + bdd.describe('Count API', function postIngest() { - bdd.before(function () { + bdd.before(function () { + return scenarioManager.client.create({ + index: 'foo-1', + type: 'bar', + id: '1', + body: { + foo: 'bar' + } + }) + .then(function () { return scenarioManager.client.create({ - index: 'foo-1', + index: 'foo-2', type: 'bar', - id: '1', + id: '2', body: { foo: 'bar' } - }) - .then(function () { - return scenarioManager.client.create({ - index: 'foo-2', - type: 'bar', - id: '2', - body: { - foo: 'bar' - } - }); - }) - .then(function () { - return scenarioManager.client.indices.refresh({ - index: ['foo-1', 'foo-2'] - }); + }); + }) + .then(function () { + return scenarioManager.client.indices.refresh({ + index: ['foo-1', 'foo-2'] }); }); + }); - bdd.after(function () { - return scenarioManager.reload('emptyKibana') - .then(function () { - scenarioManager.client.indices.delete({ - index: 'foo*' - }); + bdd.after(function () { + return scenarioManager.reload('emptyKibana') + .then(function () { + scenarioManager.client.indices.delete({ + index: 'foo*' }); }); + }); + + bdd.it('should return 200 with a document count for existing indices', function () { + return request.post('/kibana/foo-*/_count') + .expect(200) + .then(function (response) { + expect(response.body.count).to.be(2); + }); + }); - bdd.it('should return 200 with a document count for existing indices', function () { - return request.post('/kibana/foo-*/_count') + bdd.it('should support GET requests as well', function () { + return request.get('/kibana/foo-*/_count') .expect(200) .then(function (response) { expect(response.body.count).to.be(2); }); - }); + }); - bdd.it('should support GET requests as well', function () { - return request.get('/kibana/foo-*/_count') - .expect(200) - .then(function (response) { - expect(response.body.count).to.be(2); - }); - }); + bdd.it('should return 404 if a pattern matches no indices', function () { + return request.post('/kibana/doesnotexist-*/_count') + .expect(404); + }); - bdd.it('should return 404 if a pattern matches no indices', function () { - return request.post('/kibana/doesnotexist-*/_count') + bdd.it('should return 404 if a concrete index does not exist', function () { + return request.post('/kibana/concrete/_count') .expect(404); - }); - - bdd.it('should return 404 if a concrete index does not exist', function () { - return request.post('/kibana/concrete/_count') - .expect(404); - }); - }); - }; -}); + + }); +}; diff --git a/test/unit/api/search/index.js b/test/unit/api/search/index.js index 85fd81bc12253..7e430e01dbd9c 100644 --- a/test/unit/api/search/index.js +++ b/test/unit/api/search/index.js @@ -1,23 +1,21 @@ -define(function (require) { - var bdd = require('intern!bdd'); - var serverConfig = require('intern/dojo/node!../../../server_config'); - var ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); - var request = require('intern/dojo/node!supertest-as-promised'); - var url = require('intern/dojo/node!url'); - var count = require('./_count'); +var bdd = require('intern!bdd'); +var serverConfig = require('intern/dojo/node!../../../server_config'); +var ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); +var request = require('intern/dojo/node!supertest-as-promised'); +var url = require('intern/dojo/node!url'); +var count = require('./_count'); - bdd.describe('search API', function () { - var scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); - request = request(url.format(serverConfig.servers.kibana) + '/api'); +bdd.describe('search API', function () { + var scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); + request = request(url.format(serverConfig.servers.kibana) + '/api'); - bdd.before(function () { - return scenarioManager.load('emptyKibana'); - }); - - bdd.after(function () { - return scenarioManager.unload('emptyKibana'); - }); + bdd.before(function () { + return scenarioManager.load('emptyKibana'); + }); - count(bdd, scenarioManager, request); + bdd.after(function () { + return scenarioManager.unload('emptyKibana'); }); + + count(bdd, scenarioManager, request); }); diff --git a/test/visual_regression/index.js b/test/visual_regression/index.js index 17bec9761f36e..7d9e0985c36b8 100644 --- a/test/visual_regression/index.js +++ b/test/visual_regression/index.js @@ -1,26 +1,24 @@ -define(function (require) { - require('intern/dojo/node!../support/env_setup'); +require('intern/dojo/node!../support/env_setup'); - const bdd = require('intern!bdd'); - const intern = require('intern'); - const initCallbacks = []; +const bdd = require('intern!bdd'); +const intern = require('intern'); +const initCallbacks = []; - function onInit(callback) { - initCallbacks.push(callback); - } +function onInit(callback) { + initCallbacks.push(callback); +} - global.__kibana__intern__ = { intern, bdd, onInit }; +global.__kibana__intern__ = { intern, bdd, onInit }; - bdd.describe('Kibana visual regressions', function () { - bdd.before(function () { - initCallbacks.forEach(callback => { - callback.call(this); - }); +bdd.describe('Kibana visual regressions', function () { + bdd.before(function () { + initCallbacks.forEach(callback => { + callback.call(this); }); - - require([ - 'intern/dojo/node!../support/index', - 'intern/dojo/node!./home', - ], function () {}); }); + + require([ + 'intern/dojo/node!../support/index', + 'intern/dojo/node!./home', + ], function () {}); }); From b7d3f9535a508e17c5ca131cc3163032e94af8cf Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 9 Sep 2016 18:49:42 -0700 Subject: [PATCH 08/33] ignore copy-pasted decode geohash code --- .eslintignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.eslintignore b/.eslintignore index 5e30ee48846ae..94357790433f7 100644 --- a/.eslintignore +++ b/.eslintignore @@ -6,3 +6,4 @@ /src/core_plugins/console/public/tests/webpackShims /src/core_plugins/timelion/bower_components /src/core_plugins/timelion/vendor_components +/src/ui/public/utils/decode_geo_hash.js From ce7e1f617a47fb480951256cacfd44eb744f0d06 Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 4 Nov 2016 12:52:52 -0700 Subject: [PATCH 09/33] re-enable no-var rule --- .eslintrc | 1 - 1 file changed, 1 deletion(-) diff --git a/.eslintrc b/.eslintrc index 1904222b3cfa9..76c42539c061c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,7 +2,6 @@ extends: '@elastic/kibana' rules: no-unused-vars: off - no-var: off prefer-const: off no-extra-semi: off quotes: off From e804e7a61e17a6a164983524273660447956383b Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 4 Nov 2016 12:56:28 -0700 Subject: [PATCH 10/33] `eslint --fix` with no-var enabled --- .../pipeline_setup/lib/keys_deep.js | 2 +- .../table_vis/public/table_vis_controller.js | 2 +- src/core_plugins/timelion/index.js | 12 ++-- src/core_plugins/timelion/init.js | 6 +- src/core_plugins/timelion/public/app.js | 28 ++++---- .../timelion/public/directives/cells/cells.js | 8 +-- .../timelion/public/directives/chart/chart.js | 8 +-- .../timelion/public/directives/docs.js | 10 +-- .../public/directives/expression_directive.js | 38 +++++------ .../public/directives/fixed_element.js | 14 ++-- .../directives/fullscreen/fullscreen.js | 8 +-- .../public/directives/interval/interval.js | 10 +-- .../public/directives/refresh_hack.js | 6 +- .../public/directives/timelion_grid.js | 12 ++-- .../timelion/public/lib/observe_resize.js | 6 +- .../public/panels/timechart/schema.js | 66 +++++++++---------- .../public/panels/timechart/timechart.js | 4 +- .../panels/timechart/xaxis_formatter.js | 6 +- .../public/services/dashboard_context.js | 12 ++-- .../timelion/public/services/saved_sheets.js | 10 +-- src/core_plugins/timelion/public/vis/index.js | 2 +- .../public/vis/timelion_vis_controller.js | 16 ++--- .../vis/timelion_vis_params_controller.js | 2 +- .../server/fit_functions/__test__/average.js | 22 +++---- .../server/fit_functions/__test__/carry.js | 22 +++---- .../timelion/server/fit_functions/average.js | 30 ++++----- .../timelion/server/fit_functions/carry.js | 10 +-- .../timelion/server/fit_functions/nearest.js | 10 +-- .../timelion/server/fit_functions/scale.js | 20 +++--- .../timelion/server/handlers/chain_runner.js | 58 ++++++++-------- .../timelion/server/handlers/lib/arg_type.js | 2 +- .../server/handlers/lib/index_arguments.js | 14 ++-- .../server/handlers/lib/parse_sheet.js | 14 ++-- .../server/handlers/lib/preprocess_chain.js | 4 +- .../handlers/lib/reposition_arguments.js | 14 ++-- .../timelion/server/handlers/lib/tl_config.js | 8 +-- .../server/handlers/lib/validate_arg.js | 12 ++-- .../server/handlers/lib/validate_time.js | 12 ++-- .../server/lib/__test__/load_functions.js | 4 +- src/core_plugins/timelion/server/lib/alter.js | 8 +-- .../timelion/server/lib/asSorted.js | 6 +- .../timelion/server/lib/build_target.js | 14 ++-- .../timelion/server/lib/classes/chainable.js | 2 +- .../timelion/server/lib/classes/datasource.js | 16 ++--- .../server/lib/classes/timelion_function.js | 14 ++-- .../timelion/server/lib/date_math.js | 28 ++++---- .../timelion/server/lib/functions_md.js | 14 ++-- .../server/lib/get_namespaced_settings.js | 6 +- .../timelion/server/lib/load_functions.js | 22 +++---- .../timelion/server/lib/offset_time.js | 10 +-- .../server/lib/process_function_definition.js | 6 +- .../timelion/server/lib/reduce.js | 14 ++-- .../timelion/server/lib/split_interval.js | 2 +- .../timelion/server/lib/to_milliseconds.js | 14 ++-- .../timelion/server/lib/unzipPairs.js | 4 +- .../timelion/server/routes/functions.js | 4 +- .../timelion/server/routes/run.js | 18 ++--- .../timelion/server/routes/validate_es.js | 6 +- .../server/series_functions/__tests__/abs.js | 16 ++--- .../server/series_functions/__tests__/bars.js | 18 ++--- .../series_functions/__tests__/condition.js | 18 ++--- .../server/series_functions/__tests__/es.js | 2 +- .../series_functions/__tests__/first.js | 10 +-- .../server/series_functions/__tests__/fit.js | 24 +++---- .../__tests__/fixtures/bucketList.js | 2 +- .../__tests__/fixtures/seriesList.js | 10 +-- .../__tests__/fixtures/tlConfig.js | 6 +- .../series_functions/__tests__/graphite.js | 16 ++--- .../__tests__/helpers/get_series.js | 4 +- .../__tests__/helpers/get_series_list.js | 2 +- .../helpers/get_single_series_list.js | 6 +- .../__tests__/helpers/invoke_series_fn.js | 10 +-- .../series_functions/__tests__/movingstd.js | 2 +- .../series_functions/__tests__/points.js | 2 +- .../series_functions/__tests__/quandl.js | 24 +++---- .../timelion/server/series_functions/abs.js | 8 +-- .../timelion/server/series_functions/bars.js | 4 +- .../timelion/server/series_functions/color.js | 10 +-- .../server/series_functions/condition.js | 20 +++--- .../timelion/server/series_functions/cusum.js | 10 +-- .../server/series_functions/derivative.js | 8 +-- .../server/series_functions/divide.js | 4 +- .../server/series_functions/es/index.js | 16 ++--- .../es/lib/agg_response_to_series_list.js | 8 +-- .../series_functions/es/lib/build_request.js | 12 ++-- .../es/lib/create_date_agg.js | 6 +- .../timelion/server/series_functions/first.js | 4 +- .../timelion/server/series_functions/fit.js | 12 ++-- .../server/series_functions/graphite.js | 18 ++--- .../timelion/server/series_functions/hide.js | 4 +- .../server/series_functions/holt/index.js | 16 ++--- .../server/series_functions/holt/lib/des.js | 18 ++--- .../server/series_functions/holt/lib/ses.js | 2 +- .../server/series_functions/holt/lib/tes.js | 30 ++++----- .../timelion/server/series_functions/label.js | 8 +-- .../server/series_functions/legend.js | 4 +- .../timelion/server/series_functions/lines.js | 4 +- .../timelion/server/series_functions/log.js | 10 +-- .../timelion/server/series_functions/max.js | 4 +- .../timelion/server/series_functions/min.js | 4 +- .../server/series_functions/movingaverage.js | 18 ++--- .../server/series_functions/movingstd.js | 12 ++-- .../server/series_functions/multiply.js | 4 +- .../server/series_functions/points.js | 8 +-- .../server/series_functions/precision.js | 6 +- .../timelion/server/series_functions/props.js | 18 ++--- .../server/series_functions/quandl.js | 18 ++--- .../timelion/server/series_functions/range.js | 16 ++--- .../server/series_functions/scale_interval.js | 14 ++-- .../server/series_functions/static.js | 22 +++---- .../server/series_functions/subtract.js | 4 +- .../timelion/server/series_functions/sum.js | 4 +- .../timelion/server/series_functions/title.js | 4 +- .../server/series_functions/trend/index.js | 6 +- .../series_functions/trend/lib/regress.js | 30 ++++----- .../timelion/server/series_functions/trim.js | 10 +-- .../server/series_functions/worldbank.js | 24 +++---- .../series_functions/worldbank_indicators.js | 22 +++---- .../timelion/server/series_functions/yaxis.js | 6 +- .../__tests__/paginated_selectable_list.js | 6 +- .../__tests__/kbn_top_nav_controller.js | 4 +- .../public/paginated_table/__tests__/index.js | 4 +- .../public/pattern_checker/pattern_checker.js | 2 +- .../lib/layout/splits/column_chart/splits.js | 6 +- tasks/build/babel_options.js | 8 +-- tasks/build/install_npm_deps.js | 4 +- tasks/build/shasums.js | 12 ++-- tasks/config/esvm.js | 8 +-- tasks/config/intern.js | 2 +- tasks/config/s3.js | 2 +- tasks/release_packages.js | 2 +- tasks/sterilize.js | 2 +- tasks/utils/install_or_update_repo.js | 10 +-- tasks/utils/update_version.js | 14 ++-- test/fixtures/__tests__/scenario_manager.js | 40 +++++------ test/fixtures/config.js | 4 +- test/fixtures/scenario_manager.js | 30 ++++----- test/functional/apps/dashboard/_dashboard.js | 10 +-- .../apps/discover/_collapse_expand.js | 4 +- test/functional/apps/discover/_field_data.js | 24 +++---- .../functional/apps/discover/_shared_links.js | 14 ++-- .../apps/discover/_source_filters.js | 6 +- .../apps/management/_creation_form_changes.js | 8 +-- .../_index_pattern_create_delete.js | 6 +- .../management/_index_pattern_popularity.js | 2 +- .../management/_index_pattern_results_sort.js | 2 +- .../apps/management/_initial_state.js | 2 +- test/functional/apps/visualize/_area_chart.js | 16 ++--- .../functional/apps/visualize/_chart_types.js | 2 +- test/functional/apps/visualize/_data_table.js | 10 +-- test/functional/apps/visualize/_line_chart.js | 20 +++--- .../apps/visualize/_metric_chart.js | 24 +++---- test/functional/apps/visualize/_pie_chart.js | 12 ++-- test/functional/apps/visualize/_tile_map.js | 16 ++--- .../apps/visualize/_vertical_bar_chart.js | 10 +-- test/functional/apps/visualize/index.js | 2 +- test/functional/status_page/index.js | 4 +- test/mocha_setup.js | 6 +- test/server_config.js | 4 +- test/support/env_setup.js | 2 +- test/support/page_objects/common.js | 28 ++++---- test/support/page_objects/dashboard_page.js | 8 +-- test/support/page_objects/discover_page.js | 2 +- test/support/page_objects/header_page.js | 2 +- test/support/page_objects/settings_page.js | 18 ++--- test/support/page_objects/shield_page.js | 2 +- test/support/page_objects/visualize_page.js | 58 ++++++++-------- test/support/utils/elastic_dump.js | 20 +++--- test/support/utils/es_client.js | 20 +++--- test/support/utils/try.js | 12 ++-- test/unit/api/ingest/_field_capabilities.js | 12 ++-- test/unit/api/ingest/_processors.js | 6 +- test/unit/api/ingest/_simulate.js | 8 +-- test/unit/api/ingest/index.js | 24 +++---- test/unit/api/ingest/processors/_append.js | 6 +- test/unit/api/ingest/processors/_convert.js | 6 +- test/unit/api/ingest/processors/_date.js | 8 +-- test/unit/api/ingest/processors/_geoip.js | 6 +- test/unit/api/ingest/processors/_grok.js | 6 +- test/unit/api/ingest/processors/_gsub.js | 6 +- test/unit/api/ingest/processors/_join.js | 6 +- test/unit/api/ingest/processors/_lowercase.js | 6 +- test/unit/api/ingest/processors/_remove.js | 6 +- test/unit/api/ingest/processors/_rename.js | 6 +- test/unit/api/ingest/processors/_set.js | 6 +- test/unit/api/ingest/processors/_split.js | 6 +- test/unit/api/ingest/processors/_trim.js | 6 +- test/unit/api/ingest/processors/_uppercase.js | 6 +- test/unit/api/ingest/processors/index.js | 28 ++++---- test/unit/api/scripts/_languages.js | 2 +- test/unit/api/scripts/index.js | 10 +-- test/unit/api/search/_count.js | 6 +- test/unit/api/search/index.js | 14 ++-- test/utils/__tests__/get_page.js | 8 +-- test/utils/get_url.js | 4 +- test/visual_regression/home/_loading.js | 2 +- 196 files changed, 1080 insertions(+), 1080 deletions(-) diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js index 6485f55344d81..5b5976583f132 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js @@ -5,7 +5,7 @@ export default function keysDeep(object, base) { let delimitedBase = base ? base + '.' : ''; _.forEach(object, (value, key) => { - var fullKey = delimitedBase + key; + let fullKey = delimitedBase + key; if (_.isPlainObject(value)) { result = result.concat(keysDeep(value, fullKey)); } else { diff --git a/src/core_plugins/table_vis/public/table_vis_controller.js b/src/core_plugins/table_vis/public/table_vis_controller.js index e48484b93f98c..fbd572a5e8575 100644 --- a/src/core_plugins/table_vis/public/table_vis_controller.js +++ b/src/core_plugins/table_vis/public/table_vis_controller.js @@ -11,7 +11,7 @@ const module = uiModules.get('kibana/table_vis', ['kibana']); module.controller('KbnTableVisController', function ($scope, Private) { const tabifyAggResponse = Private(AggResponseTabifyTabifyProvider); - var uiStateSort = ($scope.uiState) ? $scope.uiState.get('vis.params.sort') : {}; + let uiStateSort = ($scope.uiState) ? $scope.uiState.get('vis.params.sort') : {}; assign($scope.vis.params.sort, uiStateSort); $scope.sort = $scope.vis.params.sort; diff --git a/src/core_plugins/timelion/index.js b/src/core_plugins/timelion/index.js index 6221d6ed03700..51b8220a75001 100644 --- a/src/core_plugins/timelion/index.js +++ b/src/core_plugins/timelion/index.js @@ -1,12 +1,12 @@ -var path = require('path'); +let path = require('path'); module.exports = function (kibana) { - var mainFile = 'plugins/timelion/app'; + let mainFile = 'plugins/timelion/app'; - var ownDescriptor = Object.getOwnPropertyDescriptor(kibana, 'autoload'); - var protoDescriptor = Object.getOwnPropertyDescriptor(kibana.constructor.prototype, 'autoload'); - var descriptor = ownDescriptor || protoDescriptor || {}; + let ownDescriptor = Object.getOwnPropertyDescriptor(kibana, 'autoload'); + let protoDescriptor = Object.getOwnPropertyDescriptor(kibana.constructor.prototype, 'autoload'); + let descriptor = ownDescriptor || protoDescriptor || {}; if (descriptor.get) { // the autoload list has been replaced with a getter that complains about // improper access, bypass that getter by seeing if it is defined @@ -23,7 +23,7 @@ module.exports = function (kibana) { icon: 'plugins/timelion/icon.svg', main: mainFile, injectVars: function (server, options) { - var config = server.config(); + let config = server.config(); return { kbnIndex: config.get('kibana.index'), esShardTimeout: config.get('elasticsearch.shardTimeout'), diff --git a/src/core_plugins/timelion/init.js b/src/core_plugins/timelion/init.js index 36fb506d8de62..5bd30de7de37d 100644 --- a/src/core_plugins/timelion/init.js +++ b/src/core_plugins/timelion/init.js @@ -1,5 +1,5 @@ -var _ = require('lodash'); -var processFunctionDefinition = require('./server/lib/process_function_definition'); +let _ = require('lodash'); +let processFunctionDefinition = require('./server/lib/process_function_definition'); module.exports = function (server) { //var config = server.config(); @@ -8,7 +8,7 @@ module.exports = function (server) { require('./server/routes/functions.js')(server); require('./server/routes/validate_es.js')(server); - var functions = require('./server/lib/load_functions')('series_functions'); + let functions = require('./server/lib/load_functions')('series_functions'); function addFunction(func) { _.assign(functions, processFunctionDefinition(func)); diff --git a/src/core_plugins/timelion/public/app.js b/src/core_plugins/timelion/public/app.js index be8d263a0afa4..adba360dba35d 100644 --- a/src/core_plugins/timelion/public/app.js +++ b/src/core_plugins/timelion/public/app.js @@ -1,6 +1,6 @@ -var _ = require('lodash'); -var logoUrl = require('./logo.png'); -var moment = require('moment-timezone'); +let _ = require('lodash'); +let logoUrl = require('./logo.png'); +let moment = require('moment-timezone'); require('plugins/timelion/directives/cells/cells'); require('plugins/timelion/directives/fullscreen/fullscreen'); @@ -15,7 +15,7 @@ document.title = 'Timelion - Kibana'; require('ui/chrome'); -var app = require('ui/modules').get('apps/timelion', []); +let app = require('ui/modules').get('apps/timelion', []); require('plugins/timelion/services/saved_sheets'); require('plugins/timelion/services/_saved_sheet'); @@ -27,7 +27,7 @@ require('./vis'); require('ui/saved_objects/saved_object_registry').register(require('plugins/timelion/services/saved_sheet_register')); // TODO: Expose an api for dismissing notifications -var unsafeNotifications = require('ui/notify')._notifs; +let unsafeNotifications = require('ui/notify')._notifs; //var ConfigTemplate = require('ui/config_template'); require('ui/routes').enable(); @@ -53,16 +53,16 @@ app.controller('timelion', function ( moment.tz.setDefault(config.get('dateFormat:tz')); timefilter.enabled = true; - var notify = new Notifier({ + let notify = new Notifier({ location: 'Timelion' }); - var timezone = Private(require('plugins/timelion/services/timezone'))(); - var docTitle = Private(require('ui/doc_title')); + let timezone = Private(require('plugins/timelion/services/timezone'))(); + let docTitle = Private(require('ui/doc_title')); - var defaultExpression = '.es(*)'; - var savedSheet = $route.current.locals.savedSheet; - var blankSheet = [defaultExpression]; + let defaultExpression = '.es(*)'; + let savedSheet = $route.current.locals.savedSheet; + let blankSheet = [defaultExpression]; $scope.topNavMenu = [{ key: 'new', @@ -109,7 +109,7 @@ app.controller('timelion', function ( }; } - var init = function () { + let init = function () { $scope.running = false; $scope.search(); @@ -129,7 +129,7 @@ app.controller('timelion', function ( }; }; - var refresher; + let refresher; $scope.$watchCollection('timefilter.refreshInterval', function (interval) { if (refresher) $timeout.cancel(refresher); if (interval.value > 0 && !interval.pause) { @@ -192,7 +192,7 @@ app.controller('timelion', function ( $scope.sheet = []; $scope.running = false; - var err = new Error(resp.message); + let err = new Error(resp.message); err.stack = resp.stack; notify.error(err); diff --git a/src/core_plugins/timelion/public/directives/cells/cells.js b/src/core_plugins/timelion/public/directives/cells/cells.js index fb23e3f9aad64..40d1ecfbff99c 100644 --- a/src/core_plugins/timelion/public/directives/cells/cells.js +++ b/src/core_plugins/timelion/public/directives/cells/cells.js @@ -1,12 +1,12 @@ -var _ = require('lodash'); -var $ = require('jquery'); +let _ = require('lodash'); +let $ = require('jquery'); require('angularSortableView'); require('plugins/timelion/directives/chart/chart'); require('plugins/timelion/directives/timelion_grid'); -var app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); -var html = require('./cells.html'); +let app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); +let html = require('./cells.html'); app.directive('timelionCells', function () { return { diff --git a/src/core_plugins/timelion/public/directives/chart/chart.js b/src/core_plugins/timelion/public/directives/chart/chart.js index 5e88240053d54..cce425f7e7a6c 100644 --- a/src/core_plugins/timelion/public/directives/chart/chart.js +++ b/src/core_plugins/timelion/public/directives/chart/chart.js @@ -1,4 +1,4 @@ -var panelRegistryProvider = require('plugins/timelion/lib/panel_registry'); +let panelRegistryProvider = require('plugins/timelion/lib/panel_registry'); require('ui/modules') .get('apps/timelion', []) @@ -12,8 +12,8 @@ require('ui/modules') }, link: function ($scope, $elem) { - var panelRegistry = Private(panelRegistryProvider); - var panelScope = $scope.$new(true); + let panelRegistry = Private(panelRegistryProvider); + let panelScope = $scope.$new(true); function render(seriesList) { panelScope.$destroy(); @@ -24,7 +24,7 @@ require('ui/modules') type: 'timechart' }; - var panelSchema = panelRegistry.byName[seriesList.render.type]; + let panelSchema = panelRegistry.byName[seriesList.render.type]; if (!panelSchema) { $elem.text('No such panel type: ' + seriesList.render.type); diff --git a/src/core_plugins/timelion/public/directives/docs.js b/src/core_plugins/timelion/public/directives/docs.js index e7390e105043b..a034f50461e9e 100644 --- a/src/core_plugins/timelion/public/directives/docs.js +++ b/src/core_plugins/timelion/public/directives/docs.js @@ -1,7 +1,7 @@ -var html = require('../partials/docs/tutorial.html'); -var app = require('ui/modules').get('apps/timelion', []); -var _ = require('lodash'); -var moment = require('moment'); +let html = require('../partials/docs/tutorial.html'); +let app = require('ui/modules').get('apps/timelion', []); +let _ = require('lodash'); +let moment = require('moment'); app.directive('timelionDocs', function (config, $http) { return { @@ -49,7 +49,7 @@ app.directive('timelionDocs', function (config, $http) { $scope.es.valid = false; $scope.es.invalidReason = (function () { try { - var esResp = JSON.parse(resp.data.resp.response); + let esResp = JSON.parse(resp.data.resp.response); return _.get(esResp, 'error.root_cause[0].reason'); } catch (e) { if (_.get(resp, 'data.resp.message')) return _.get(resp, 'data.resp.message'); diff --git a/src/core_plugins/timelion/public/directives/expression_directive.js b/src/core_plugins/timelion/public/directives/expression_directive.js index 53a42db1c9254..8df3e1b15220b 100644 --- a/src/core_plugins/timelion/public/directives/expression_directive.js +++ b/src/core_plugins/timelion/public/directives/expression_directive.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); -var $ = require('jquery'); -var grammar = require('raw!../chain.peg'); -var PEG = require('pegjs'); -var Parser = PEG.buildParser(grammar); -var template = require('./partials/suggestion.html'); +let _ = require('lodash'); +let $ = require('jquery'); +let grammar = require('raw!../chain.peg'); +let PEG = require('pegjs'); +let Parser = PEG.buildParser(grammar); +let template = require('./partials/suggestion.html'); -var app = require('ui/modules').get('apps/timelion', []); +let app = require('ui/modules').get('apps/timelion', []); /* Autocomplete proposal, this file doesn't actually work like this @@ -40,7 +40,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc require: 'ngModel', link: function ($scope, $elem, $attrs, ngModelCtrl) { - var keys = { + let keys = { ESC: 27, UP: 38, DOWN: 40, @@ -48,7 +48,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc ENTER: 13 }; - var functionReference = {}; + let functionReference = {}; function init() { resetSuggestions(); @@ -81,7 +81,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc function suggest(val) { try { // Inside an existing function providing suggestion only as a reference. Maybe suggest an argument? - var possible = findFunction(getCaretPos(), Parser.parse(val).functions); + let possible = findFunction(getCaretPos(), Parser.parse(val).functions); // TODO: Reference suggestors. Only supporting completion right now; resetSuggestions(); return; @@ -124,20 +124,20 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc } function validateSelection() { - var maxSelection = $scope.suggestions.list.length - 1; + let maxSelection = $scope.suggestions.list.length - 1; if ($scope.suggestions.selected > maxSelection) $scope.suggestions.selected = maxSelection; else if ($scope.suggestions.selected < 0) $scope.suggestions.selected = 0; } $scope.completeExpression = function (selected) { if (!$scope.suggestions.list.length) return; - var expression = $attrs.timelionExpression; - var startOf = expression.slice(0, $scope.suggestions.location.min); - var endOf = expression.slice($scope.suggestions.location.max, expression.length); + let expression = $attrs.timelionExpression; + let startOf = expression.slice(0, $scope.suggestions.location.min); + let endOf = expression.slice($scope.suggestions.location.max, expression.length); - var completeFunction = $scope.suggestions.list[selected].name + '()'; + let completeFunction = $scope.suggestions.list[selected].name + '()'; - var newVal = startOf + completeFunction + endOf; + let newVal = startOf + completeFunction + endOf; $elem.val(newVal); $elem[0].selectionStart = $elem[0].selectionEnd = @@ -195,8 +195,8 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc function scrollTo(suggestions) { validateSelection(); - var suggestionsListElem = $('.suggestions'); - var suggestedElem = $($('.suggestion')[suggestions.selected]); + let suggestionsListElem = $('.suggestions'); + let suggestedElem = $($('.suggestion')[suggestions.selected]); if (!suggestedElem.position() || !suggestedElem.position().top) return; @@ -204,7 +204,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc } function findFunction(position, functionList) { - var bestFunction; + let bestFunction; _.each(functionList, function (func) { if ((func.location.min) < position && position < (func.location.max)) { diff --git a/src/core_plugins/timelion/public/directives/fixed_element.js b/src/core_plugins/timelion/public/directives/fixed_element.js index 1efa8bce6de29..d98a08a6eb9d8 100644 --- a/src/core_plugins/timelion/public/directives/fixed_element.js +++ b/src/core_plugins/timelion/public/directives/fixed_element.js @@ -1,16 +1,16 @@ -var _ = require('lodash'); -var $ = require('jquery'); +let _ = require('lodash'); +let $ = require('jquery'); -var app = require('ui/modules').get('apps/timelion', []); +let app = require('ui/modules').get('apps/timelion', []); app.directive('fixedElementRoot', function ($timeout) { return { restrict: 'A', link: function ($scope, $elem, attrs) { - var fixedAt; + let fixedAt; $(window).bind('scroll', function () { - var fixed = $('[fixed-element]', $elem); - var body = $('[fixed-element-body]', $elem); - var top = fixed.offset().top; + let fixed = $('[fixed-element]', $elem); + let body = $('[fixed-element-body]', $elem); + let top = fixed.offset().top; if ($(window).scrollTop() > top) { // This is a gross hack, but its better than it was. I guess diff --git a/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js b/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js index a2353c27c3bc0..ae60626ed5a3a 100644 --- a/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js +++ b/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js @@ -1,12 +1,12 @@ -var _ = require('lodash'); -var $ = require('jquery'); +let _ = require('lodash'); +let $ = require('jquery'); require('angularSortableView'); require('plugins/timelion/directives/chart/chart'); require('plugins/timelion/directives/timelion_grid'); -var app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); -var html = require('./fullscreen.html'); +let app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); +let html = require('./fullscreen.html'); app.directive('timelionFullscreen', function () { return { diff --git a/src/core_plugins/timelion/public/directives/interval/interval.js b/src/core_plugins/timelion/public/directives/interval/interval.js index f0266eb601d8f..28c2191b051bb 100644 --- a/src/core_plugins/timelion/public/directives/interval/interval.js +++ b/src/core_plugins/timelion/public/directives/interval/interval.js @@ -1,9 +1,9 @@ -var _ = require('lodash'); -var $ = require('jquery'); -var moment = require('moment'); +let _ = require('lodash'); +let $ = require('jquery'); +let moment = require('moment'); -var app = require('ui/modules').get('apps/timelion', []); -var html = require('./interval.html'); +let app = require('ui/modules').get('apps/timelion', []); +let html = require('./interval.html'); app.directive('timelionInterval', function ($compile, $timeout, timefilter) { return { diff --git a/src/core_plugins/timelion/public/directives/refresh_hack.js b/src/core_plugins/timelion/public/directives/refresh_hack.js index 131f00a26205e..8a923ed623f1a 100644 --- a/src/core_plugins/timelion/public/directives/refresh_hack.js +++ b/src/core_plugins/timelion/public/directives/refresh_hack.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); -var $ = require('jquery'); +let _ = require('lodash'); +let $ = require('jquery'); -var app = require('ui/modules').get('apps/timelion', []); +let app = require('ui/modules').get('apps/timelion', []); app.directive('refreshHack', function ($rootScope) { return { diff --git a/src/core_plugins/timelion/public/directives/timelion_grid.js b/src/core_plugins/timelion/public/directives/timelion_grid.js index 5b4da83962324..0af069cd3167c 100644 --- a/src/core_plugins/timelion/public/directives/timelion_grid.js +++ b/src/core_plugins/timelion/public/directives/timelion_grid.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); -var $ = require('jquery'); +let _ = require('lodash'); +let $ = require('jquery'); -var app = require('ui/modules').get('apps/timelion', []); +let app = require('ui/modules').get('apps/timelion', []); app.directive('timelionGrid', function ($compile) { return { restrict: 'A', @@ -28,9 +28,9 @@ app.directive('timelionGrid', function ($compile) { }); function setDimensions() { - var borderSize = 2; - var headerSize = 45 + 35 + 28 + (20 * 2); // chrome + subnav + buttons + (container padding) - var verticalPadding = 10; + let borderSize = 2; + let headerSize = 45 + 35 + 28 + (20 * 2); // chrome + subnav + buttons + (container padding) + let verticalPadding = 10; if ($scope.timelionGridColumns != null) { $elem.width($elem.parent().width() / $scope.timelionGridColumns - (borderSize * 2)); diff --git a/src/core_plugins/timelion/public/lib/observe_resize.js b/src/core_plugins/timelion/public/lib/observe_resize.js index 91c68f7cc7a05..9647631bc8ac2 100644 --- a/src/core_plugins/timelion/public/lib/observe_resize.js +++ b/src/core_plugins/timelion/public/lib/observe_resize.js @@ -1,10 +1,10 @@ module.exports = function ($elem, fn, frequency) { frequency = frequency || 500; - var currentHeight = $elem.height(); - var currentWidth = $elem.width(); + let currentHeight = $elem.height(); + let currentWidth = $elem.width(); - var timeout; + let timeout; function checkLoop() { timeout = setTimeout(function () { diff --git a/src/core_plugins/timelion/public/panels/timechart/schema.js b/src/core_plugins/timelion/public/panels/timechart/schema.js index b3c742321ddcb..5a01182ac51a9 100644 --- a/src/core_plugins/timelion/public/panels/timechart/schema.js +++ b/src/core_plugins/timelion/public/panels/timechart/schema.js @@ -1,33 +1,33 @@ require('./flot'); require('plugins/timelion/panels/timechart/timechart.less'); -var _ = require('lodash'); -var $ = require('jquery'); -var moment = require('moment-timezone'); -var observeResize = require('plugins/timelion/lib/observe_resize'); -var calculateInterval = require('plugins/timelion/lib/calculate_interval'); +let _ = require('lodash'); +let $ = require('jquery'); +let moment = require('moment-timezone'); +let observeResize = require('plugins/timelion/lib/observe_resize'); +let calculateInterval = require('plugins/timelion/lib/calculate_interval'); module.exports = function timechartFn(Private, config, $rootScope, timefilter, $compile) { return function () { return { help: 'Draw a timeseries chart', render: function ($scope, $elem) { - var template = '
'; - var timezone = Private(require('plugins/timelion/services/timezone'))(); - var getxAxisFormatter = Private(require('plugins/timelion/panels/timechart/xaxis_formatter')); + let template = '
'; + let timezone = Private(require('plugins/timelion/services/timezone'))(); + let getxAxisFormatter = Private(require('plugins/timelion/panels/timechart/xaxis_formatter')); // TODO: I wonder if we should supply our own moment that sets this every time? // could just use angular's injection to provide a moment service? moment.tz.setDefault(config.get('dateFormat:tz')); - var render = $scope.seriesList.render || {}; + let render = $scope.seriesList.render || {}; $scope.chart = $scope.seriesList.list; $scope.interval = $scope.interval; $scope.search = $scope.search || _.noop; - var legendValueNumbers; - var debouncedSetLegendNumbers; - var defaultOptions = { + let legendValueNumbers; + let debouncedSetLegendNumbers; + let defaultOptions = { xaxis: { mode: 'time', tickLength: 5, @@ -65,12 +65,12 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ $scope.toggleSeries = function (id) { - var series = $scope.chart[id]; + let series = $scope.chart[id]; series._hide = !series._hide; drawPlot($scope.chart); }; - var cancelResize = observeResize($elem, function () { + let cancelResize = observeResize($elem, function () { drawPlot($scope.chart); }); @@ -108,7 +108,7 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ clearLegendNumbers(); }); - var debounceDelay = 50; + let debounceDelay = 50; debouncedSetLegendNumbers = _.debounce(setLegendNumbers, debounceDelay, { maxWait: debounceDelay, leading: true, @@ -117,20 +117,20 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ // Shamelessly borrowed from the flotCrosshairs example function setLegendNumbers(pos) { - var plot = $scope.plot; + let plot = $scope.plot; - var axes = plot.getAxes(); + let axes = plot.getAxes(); if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max) { return; } - var i; - var j; - var dataset = plot.getData(); + let i; + let j; + let dataset = plot.getData(); for (i = 0; i < dataset.length; ++i) { - var series = dataset[i]; - var precision = _.get(series, '_meta.precision', 2); + let series = dataset[i]; + let precision = _.get(series, '_meta.precision', 2); if (series._hide) continue; @@ -139,7 +139,7 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ if (series.data[j][0] > pos.x) break; } - var y; + let y; try { y = series.data[j][1]; } catch (e) { @@ -160,7 +160,7 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ }); } - var legendScope = $scope.$new(); + let legendScope = $scope.$new(); function drawPlot(plotConfig) { if (!plotConfig || !plotConfig.length) { @@ -169,22 +169,22 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ } if (!$('.chart-canvas', $elem).length) $elem.html(template); - var canvasElem = $('.chart-canvas', $elem); + let canvasElem = $('.chart-canvas', $elem); - var title = _(plotConfig).map('_title').compact().last(); + let title = _(plotConfig).map('_title').compact().last(); $('.chart-top-title', $elem).text(title == null ? '' : title); - var options = _.cloneDeep(defaultOptions); + let options = _.cloneDeep(defaultOptions); // Get the X-axis tick format - var time = timefilter.getBounds(); - var interval = calculateInterval( + let time = timefilter.getBounds(); + let interval = calculateInterval( time.min.valueOf(), time.max.valueOf(), config.get('timelion:target_buckets') || 200, $scope.interval ); - var format = getxAxisFormatter(interval); + let format = getxAxisFormatter(interval); // Use moment to format ticks so we get timezone correction options.xaxis.tickFormatter = function (val) { @@ -192,11 +192,11 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ }; // Calculate how many ticks can fit on the axis - var tickLetterWidth = 7; - var tickPadding = 45; + let tickLetterWidth = 7; + let tickPadding = 45; options.xaxis.ticks = Math.floor($elem.width() / ((format.length * tickLetterWidth) + tickPadding)); - var series = _.map(plotConfig, function (series, index) { + let series = _.map(plotConfig, function (series, index) { series = _.cloneDeep(_.defaults(series, { shadowSize: 0, lines: { diff --git a/src/core_plugins/timelion/public/panels/timechart/timechart.js b/src/core_plugins/timelion/public/panels/timechart/timechart.js index a7c91cdd61627..8799aaccc2683 100644 --- a/src/core_plugins/timelion/public/panels/timechart/timechart.js +++ b/src/core_plugins/timelion/public/panels/timechart/timechart.js @@ -1,5 +1,5 @@ -var Panel = require('plugins/timelion/panels/panel'); -var panelRegistry = require('plugins/timelion/lib/panel_registry'); +let Panel = require('plugins/timelion/panels/panel'); +let panelRegistry = require('plugins/timelion/lib/panel_registry'); panelRegistry.register(function timeChartProvider(Private) { // Schema is broken out so that it may be extended for use in other plugins diff --git a/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js b/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js index 8eb8f9d81f5e1..960999f91eed7 100644 --- a/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js +++ b/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js @@ -1,12 +1,12 @@ -var moment = require('moment'); +let moment = require('moment'); module.exports = function xaxisFormatterProvider(config, timefilter) { function getFormat(esInterval) { - var parts = esInterval.match(/(\d+)(ms|s|m|h|d|w|M|y|)/); + let parts = esInterval.match(/(\d+)(ms|s|m|h|d|w|M|y|)/); if (parts == null || parts[1] == null || parts[2] == null) throw new Error ('Unknown interval'); - var interval = moment.duration(Number(parts[1]), parts[2]); + let interval = moment.duration(Number(parts[1]), parts[2]); // Cribbed from Kibana's TimeBuckets class let rules = config.get('dateFormat:scaled'); diff --git a/src/core_plugins/timelion/public/services/dashboard_context.js b/src/core_plugins/timelion/public/services/dashboard_context.js index 8c6c49f218d9c..4c51b6018a839 100644 --- a/src/core_plugins/timelion/public/services/dashboard_context.js +++ b/src/core_plugins/timelion/public/services/dashboard_context.js @@ -1,20 +1,20 @@ -var _ = require('lodash'); +let _ = require('lodash'); require('ui/state_management/app_state'); module.exports = function dashboardContext(Private, getAppState) { return function () { - var queryFilter = Private(require('ui/filter_bar/query_filter')); - var bool = {must: [], must_not: []}; - var filterBarFilters = queryFilter.getFilters(); - var queryBarFilter = getAppState().query; + let queryFilter = Private(require('ui/filter_bar/query_filter')); + let bool = {must: [], must_not: []}; + let filterBarFilters = queryFilter.getFilters(); + let queryBarFilter = getAppState().query; // Add the query bar filter, its handled differently. bool.must.push(queryBarFilter); // Add each of the filter bar filters _.each(filterBarFilters, function (filter) { - var esFilter = _.omit(filter, function (val, key) { + let esFilter = _.omit(filter, function (val, key) { if (key === 'meta' || key[0] === '$') return true; return false; }); diff --git a/src/core_plugins/timelion/public/services/saved_sheets.js b/src/core_plugins/timelion/public/services/saved_sheets.js index 8586fe87429a9..6b73c9b3ea756 100644 --- a/src/core_plugins/timelion/public/services/saved_sheets.js +++ b/src/core_plugins/timelion/public/services/saved_sheets.js @@ -1,5 +1,5 @@ -var module = require('ui/modules').get('app/sheet'); -var _ = require('lodash'); +let module = require('ui/modules').get('app/sheet'); +let _ = require('lodash'); // bring in the factory require('./_saved_sheet.js'); @@ -40,8 +40,8 @@ module.service('savedSheets', function (Promise, SavedSheet, kbnIndex, es, kbnUr }; this.find = function (searchString) { - var self = this; - var body; + let self = this; + let body; if (searchString) { body = { query: { @@ -66,7 +66,7 @@ module.service('savedSheets', function (Promise, SavedSheet, kbnIndex, es, kbnUr return { total: resp.hits.total, hits: resp.hits.hits.map(function (hit) { - var source = hit._source; + let source = hit._source; source.id = hit._id; source.url = self.urlFor(hit._id); return source; diff --git a/src/core_plugins/timelion/public/vis/index.js b/src/core_plugins/timelion/public/vis/index.js index 56eb15bc1c3dc..bd6843c671f43 100644 --- a/src/core_plugins/timelion/public/vis/index.js +++ b/src/core_plugins/timelion/public/vis/index.js @@ -9,7 +9,7 @@ require('plugins/timelion/vis/timelion_vis.less'); require('ui/registry/vis_types').register(TimelionVisProvider); function TimelionVisProvider(Private) { - var TemplateVisType = Private(require('ui/template_vis_type')); + let TemplateVisType = Private(require('ui/template_vis_type')); // return the visType object, which kibana will use to display and configure new // Vis object of this type. diff --git a/src/core_plugins/timelion/public/vis/timelion_vis_controller.js b/src/core_plugins/timelion/public/vis/timelion_vis_controller.js index 9996effc5e07a..fb47690f480fd 100644 --- a/src/core_plugins/timelion/public/vis/timelion_vis_controller.js +++ b/src/core_plugins/timelion/public/vis/timelion_vis_controller.js @@ -3,19 +3,19 @@ require('plugins/timelion/directives/interval/interval'); require('plugins/timelion/directives/refresh_hack'); require('ui/state_management/app_state'); -var _ = require('lodash'); -var module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); +let _ = require('lodash'); +let module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); module.controller('TimelionVisController', function ($scope, Private, Notifier, $http, $rootScope, timefilter, getAppState) { - var queryFilter = Private(require('ui/filter_bar/query_filter')); - var timezone = Private(require('plugins/timelion/services/timezone'))(); - var dashboardContext = Private(require('plugins/timelion/services/dashboard_context')); + let queryFilter = Private(require('ui/filter_bar/query_filter')); + let timezone = Private(require('plugins/timelion/services/timezone'))(); + let dashboardContext = Private(require('plugins/timelion/services/dashboard_context')); - var notify = new Notifier({ + let notify = new Notifier({ location: 'Timelion' }); $scope.search = function run() { - var expression = $scope.vis.params.expression; + let expression = $scope.vis.params.expression; if (!expression) return; $http.post('../api/timelion/run', { @@ -36,7 +36,7 @@ module.controller('TimelionVisController', function ($scope, Private, Notifier, }) .error(function (resp) { $scope.sheet = []; - var err = new Error(resp.message); + let err = new Error(resp.message); err.stack = resp.stack; notify.error(err); }); diff --git a/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js b/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js index 1eaf89623aed7..80a997b496a77 100644 --- a/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js +++ b/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js @@ -1,6 +1,6 @@ require('plugins/timelion/directives/expression_directive'); -var module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); +let module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); module.controller('TimelionVisParamsController', function ($scope, $rootScope) { $scope.vis.params.expression = $scope.vis.params.expression || '.es(*)'; $scope.vis.params.interval = $scope.vis.params.interval || '1m'; diff --git a/src/core_plugins/timelion/server/fit_functions/__test__/average.js b/src/core_plugins/timelion/server/fit_functions/__test__/average.js index 484b9cffbaba6..606970fd8b8e0 100644 --- a/src/core_plugins/timelion/server/fit_functions/__test__/average.js +++ b/src/core_plugins/timelion/server/fit_functions/__test__/average.js @@ -1,20 +1,20 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); -var moment = require('moment'); -var expect = require('chai').expect; -var _ = require('lodash'); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); +let moment = require('moment'); +let expect = require('chai').expect; +let _ = require('lodash'); describe(filename, function () { describe('average', function () { it('fills holes in the data', function () { - var data = [ + let data = [ [moment.utc('1980', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 40], [moment.utc('1984', 'YYYY').valueOf(), 50], ]; - var target = [ + let target = [ [moment.utc('1980', 'YYYY').valueOf(), null], [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], @@ -27,13 +27,13 @@ describe(filename, function () { describe('sampling', function () { it('up', function () { - var data = [ + let data = [ [moment.utc('1981', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 30], [moment.utc('1985', 'YYYY').valueOf(), 70], ]; - var target = [ + let target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], @@ -46,7 +46,7 @@ describe(filename, function () { it('down', function () { - var data = [ + let data = [ [moment.utc('1980', 'YYYY').valueOf(), 0], [moment.utc('1981', 'YYYY').valueOf(), 2], [moment.utc('1982', 'YYYY').valueOf(), 4], @@ -56,7 +56,7 @@ describe(filename, function () { [moment.utc('1986', 'YYYY').valueOf(), 12], ]; - var target = [ + let target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], [moment.utc('1985', 'YYYY').valueOf(), null], diff --git a/src/core_plugins/timelion/server/fit_functions/__test__/carry.js b/src/core_plugins/timelion/server/fit_functions/__test__/carry.js index f719643262e48..53a71bfaee2a0 100644 --- a/src/core_plugins/timelion/server/fit_functions/__test__/carry.js +++ b/src/core_plugins/timelion/server/fit_functions/__test__/carry.js @@ -1,18 +1,18 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); -var moment = require('moment'); -var expect = require('chai').expect; -var _ = require('lodash'); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); +let moment = require('moment'); +let expect = require('chai').expect; +let _ = require('lodash'); describe(filename, function () { it('fills holes in the data', function () { - var data = [ + let data = [ [moment.utc('1980', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 40], [moment.utc('1984', 'YYYY').valueOf(), 50], ]; - var target = [ + let target = [ [moment.utc('1980', 'YYYY').valueOf(), null], [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], @@ -25,13 +25,13 @@ describe(filename, function () { describe('sampling', function () { it('up', function () { - var data = [ + let data = [ [moment.utc('1981', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 30], [moment.utc('1985', 'YYYY').valueOf(), 70], ]; - var target = [ + let target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], @@ -44,7 +44,7 @@ describe(filename, function () { it('down does not make sense', function () { - var data = [ + let data = [ [moment.utc('1980', 'YYYY').valueOf(), 0], [moment.utc('1981', 'YYYY').valueOf(), 2], [moment.utc('1982', 'YYYY').valueOf(), 4], @@ -54,7 +54,7 @@ describe(filename, function () { [moment.utc('1986', 'YYYY').valueOf(), 12], ]; - var target = [ + let target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], [moment.utc('1985', 'YYYY').valueOf(), null], diff --git a/src/core_plugins/timelion/server/fit_functions/average.js b/src/core_plugins/timelion/server/fit_functions/average.js index 4f8290e4a49b0..03eb77e7a9f5c 100644 --- a/src/core_plugins/timelion/server/fit_functions/average.js +++ b/src/core_plugins/timelion/server/fit_functions/average.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +let _ = require('lodash'); // Upsampling and down sampling of non-cummulative sets // Good: min, max, average @@ -9,12 +9,12 @@ module.exports = function (dataTuples, targetTuples) { // Phase 1: Downsample // We nessecarily won't well match the dataSource here as we don't know how much data // they had when creating their own average - var resultTimes = _.pluck(targetTuples, 0); - var dataTuplesQueue = _.clone(dataTuples); - var resultValues = _.map(targetTuples, function (bucket) { - var time = bucket[0]; - var i = 0; - var avgSet = []; + let resultTimes = _.pluck(targetTuples, 0); + let dataTuplesQueue = _.clone(dataTuples); + let resultValues = _.map(targetTuples, function (bucket) { + let time = bucket[0]; + let i = 0; + let avgSet = []; // This is naive, it doesn't consider where the line is going next, // It simply writes the point and moves on once it hits <= time. @@ -27,7 +27,7 @@ module.exports = function (dataTuples, targetTuples) { dataTuplesQueue.splice(0, i); - var sum = _.reduce(avgSet, function (sum, num) { return sum + num; }, 0); + let sum = _.reduce(avgSet, function (sum, num) { return sum + num; }, 0); return avgSet.length ? (sum / avgSet.length) : NaN; }); @@ -35,16 +35,16 @@ module.exports = function (dataTuples, targetTuples) { // Phase 2: Upsample if needed // If we have any NaNs we are probably resampling from a big interval to a small one (eg, 1M as 1d) // So look for the missing stuff in the array, and smooth it out - var naNIndex = _.findIndex(resultValues, function (val) { + let naNIndex = _.findIndex(resultValues, function (val) { return isNaN(val); }); if (naNIndex > -1) { - var i = 0; - var naNCount = 0; - var filledValues = []; - var previousRealNumber; - var stepSize; + let i = 0; + let naNCount = 0; + let filledValues = []; + let previousRealNumber; + let stepSize; while (i < resultValues.length) { if (isNaN(resultValues[i])) { if (i === 0) { @@ -70,6 +70,6 @@ module.exports = function (dataTuples, targetTuples) { } - var resultTuples = _.zip(resultTimes, resultValues); + let resultTuples = _.zip(resultTimes, resultValues); return resultTuples; }; diff --git a/src/core_plugins/timelion/server/fit_functions/carry.js b/src/core_plugins/timelion/server/fit_functions/carry.js index 6608ff438970a..75fadc2f7543b 100644 --- a/src/core_plugins/timelion/server/fit_functions/carry.js +++ b/src/core_plugins/timelion/server/fit_functions/carry.js @@ -1,5 +1,5 @@ -var _ = require('lodash'); -var moment = require('moment'); +let _ = require('lodash'); +let moment = require('moment'); // Upsampling of non-cummulative sets // Good: average, min, max @@ -12,10 +12,10 @@ module.exports = function (dataTuples, targetTuples) { throw new Error (`Don't use the 'carry' fit method to down sample, use 'scale' or 'average'`); } - var currentCarry = dataTuples[0][1]; + let currentCarry = dataTuples[0][1]; return _.map(targetTuples, function (bucket, h) { - var targetTime = bucket[0]; - var dataTime = dataTuples[0][0]; + let targetTime = bucket[0]; + let dataTime = dataTuples[0][0]; if (dataTuples[0] && targetTime >= dataTime) { currentCarry = dataTuples[0][1]; diff --git a/src/core_plugins/timelion/server/fit_functions/nearest.js b/src/core_plugins/timelion/server/fit_functions/nearest.js index 959fc2915b48c..65d528e6e9508 100644 --- a/src/core_plugins/timelion/server/fit_functions/nearest.js +++ b/src/core_plugins/timelion/server/fit_functions/nearest.js @@ -1,13 +1,13 @@ -var _ = require('lodash'); -var moment = require('moment'); +let _ = require('lodash'); +let moment = require('moment'); // Upsampling and downsampling of non-cummulative sets // Good: average, min, max // Bad: sum, count module.exports = function (dataTuples, targetTuples) { return _.map(targetTuples, function (bucket, h) { - var time = bucket[0]; - var i = 0; + let time = bucket[0]; + let i = 0; while (i < dataTuples.length - 1 && (Math.abs(dataTuples[i + 1][0] - time) < Math.abs(dataTuples[i][0] - time) || // TODO: Certain offset= args can cause buckets with duplicate times, eg, offset=-1M @@ -20,7 +20,7 @@ module.exports = function (dataTuples, targetTuples) { i++; } - var closest = dataTuples[i]; + let closest = dataTuples[i]; dataTuples.splice(0, i); return [bucket[0], closest[1]]; diff --git a/src/core_plugins/timelion/server/fit_functions/scale.js b/src/core_plugins/timelion/server/fit_functions/scale.js index b695955675816..5da08aef11e09 100644 --- a/src/core_plugins/timelion/server/fit_functions/scale.js +++ b/src/core_plugins/timelion/server/fit_functions/scale.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +let _ = require('lodash'); // Downsampling of cummulative metrics // Good: count, sum @@ -15,15 +15,15 @@ function sum(set) { module.exports = function (dataTuples, targetTuples) { - var i = 0; - var j = 0; - var spreadCount = 0; - var result = []; - var bucket; - var time; - var scaleSet; - var step; - var nextRealNumber; + let i = 0; + let j = 0; + let spreadCount = 0; + let result = []; + let bucket; + let time; + let scaleSet; + let step; + let nextRealNumber; while (i < targetTuples.length) { scaleSet = []; diff --git a/src/core_plugins/timelion/server/handlers/chain_runner.js b/src/core_plugins/timelion/server/handlers/chain_runner.js index a2b7425f4793f..993bcdfd68fab 100644 --- a/src/core_plugins/timelion/server/handlers/chain_runner.js +++ b/src/core_plugins/timelion/server/handlers/chain_runner.js @@ -1,25 +1,25 @@ -var _ = require('lodash'); -var glob = require('glob'); -var Promise = require('bluebird'); +let _ = require('lodash'); +let glob = require('glob'); +let Promise = require('bluebird'); -var parseSheet = require('./lib/parse_sheet.js'); -var parseDateMath = require('../lib/date_math.js'); -var calculateInterval = require('../../public/lib/calculate_interval.js'); +let parseSheet = require('./lib/parse_sheet.js'); +let parseDateMath = require('../lib/date_math.js'); +let calculateInterval = require('../../public/lib/calculate_interval.js'); -var repositionArguments = require('./lib/reposition_arguments.js'); -var indexArguments = require('./lib/index_arguments.js'); -var validateTime = require('./lib/validate_time.js'); +let repositionArguments = require('./lib/reposition_arguments.js'); +let indexArguments = require('./lib/index_arguments.js'); +let validateTime = require('./lib/validate_time.js'); -var loadFunctions = require('../lib/load_functions.js'); -var fitFunctions = loadFunctions('fit_functions'); +let loadFunctions = require('../lib/load_functions.js'); +let fitFunctions = loadFunctions('fit_functions'); module.exports = function (tlConfig) { - var preprocessChain = require('./lib/preprocess_chain')(tlConfig); + let preprocessChain = require('./lib/preprocess_chain')(tlConfig); - var queryCache = {}; - var stats = {}; - var sheet; + let queryCache = {}; + let stats = {}; + let sheet; function getQueryCacheKey(query) { return JSON.stringify(_.omit(query, 'label')); @@ -31,7 +31,7 @@ module.exports = function (tlConfig) { // Invokes a modifier function, resolving arguments into series as needed function invoke(fnName, args) { - var functionDef = tlConfig.server.plugins.timelion.getFunction(fnName); + let functionDef = tlConfig.server.plugins.timelion.getFunction(fnName); function resolveArgument(item) { if (_.isArray(item)) { @@ -87,16 +87,16 @@ module.exports = function (tlConfig) { function invokeChain(chainObj, result) { if (chainObj.chain.length === 0) return result[0]; - var chain = _.clone(chainObj.chain); - var link = chain.shift(); + let chain = _.clone(chainObj.chain); + let link = chain.shift(); - var promise; + let promise; if (link.type === 'chain') { promise = invokeChain(link); } else if (!result) { promise = invoke('first', [link]); } else { - var args = link.arguments ? result.concat(link.arguments) : result; + let args = link.arguments ? result.concat(link.arguments) : result; promise = invoke(link.function, args); } @@ -107,15 +107,15 @@ module.exports = function (tlConfig) { } function resolveChainList(chainList) { - var seriesList = _.map(chainList, function (chain) { - var values = invoke('first', [chain]); + let seriesList = _.map(chainList, function (chain) { + let values = invoke('first', [chain]); return values.then(function (args) { return args; }); }); return Promise.all(seriesList).then(function (args) { - var list = _.chain(args).pluck('list').flatten().value(); - var seriesList = _.merge.apply(this, _.flatten([{}, args])); + let list = _.chain(args).pluck('list').flatten().value(); + let seriesList = _.merge.apply(this, _.flatten([{}, args])); seriesList.list = list; return seriesList; }); @@ -123,10 +123,10 @@ module.exports = function (tlConfig) { function preProcessSheet(sheet) { - var queries = {}; + let queries = {}; _.each(sheet, function (chainList, i) { try { - var queriesInCell = _.mapValues(preprocessChain(chainList), function (val) { + let queriesInCell = _.mapValues(preprocessChain(chainList), function (val) { val.cell = i; return val; }); @@ -137,7 +137,7 @@ module.exports = function (tlConfig) { }); queries = _.values(queries); - var promises = _.chain(queries).values().map(function (query) { + let promises = _.chain(queries).values().map(function (query) { return invoke(query.function, query.arguments); }).value(); @@ -146,8 +146,8 @@ module.exports = function (tlConfig) { stats.queryTime = (new Date()).getTime(); _.each(queries, function (query, i) { - var functionDef = tlConfig.server.plugins.timelion.getFunction(query.function); - var resolvedDatasource = resolvedDatasources[i]; + let functionDef = tlConfig.server.plugins.timelion.getFunction(query.function); + let resolvedDatasource = resolvedDatasources[i]; if (resolvedDatasource.isRejected()) { if (resolvedDatasource.reason().isBoom) { diff --git a/src/core_plugins/timelion/server/handlers/lib/arg_type.js b/src/core_plugins/timelion/server/handlers/lib/arg_type.js index a3aa39018d72a..d034426551e21 100644 --- a/src/core_plugins/timelion/server/handlers/lib/arg_type.js +++ b/src/core_plugins/timelion/server/handlers/lib/arg_type.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function argType(arg) { if (_.isArray(arg)) { diff --git a/src/core_plugins/timelion/server/handlers/lib/index_arguments.js b/src/core_plugins/timelion/server/handlers/lib/index_arguments.js index 6630894c19b40..e90f84777e8cb 100644 --- a/src/core_plugins/timelion/server/handlers/lib/index_arguments.js +++ b/src/core_plugins/timelion/server/handlers/lib/index_arguments.js @@ -1,26 +1,26 @@ -var _ = require('lodash'); +let _ = require('lodash'); // Only applies to already resolved arguments module.exports = function indexArguments(functionDef, orderedArgs) { - var validateArg = require('./validate_arg')(functionDef); + let validateArg = require('./validate_arg')(functionDef); // This almost certainly is not required - var allowedLength = functionDef.extended ? functionDef.args.length + 2 : functionDef.args.length; + let allowedLength = functionDef.extended ? functionDef.args.length + 2 : functionDef.args.length; if (orderedArgs.length > allowedLength) throw new Error ('Too many arguments passed to: ' + functionDef.name); - var indexedArgs = {}; + let indexedArgs = {}; // Check and index each known argument _.each(functionDef.args, function (argDef, i) { - var value = orderedArgs[i]; + let value = orderedArgs[i]; validateArg(value, argDef.name, argDef); indexedArgs[argDef.name] = value; }); // Also check and index the extended arguments if enabled if (functionDef.extended) { - var values = orderedArgs[orderedArgs.length - 1]; - var names = orderedArgs[orderedArgs.length - 2]; + let values = orderedArgs[orderedArgs.length - 1]; + let names = orderedArgs[orderedArgs.length - 2]; _.each(values, function (value, i) { validateArg(value, names[i], functionDef.extended); indexedArgs[names[i]] = value; diff --git a/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js b/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js index 59f4345be4c05..35f2fd490bb55 100644 --- a/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js +++ b/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js @@ -1,16 +1,16 @@ -var fs = require('fs'); -var path = require('path'); -var _ = require('lodash'); -var grammar = fs.readFileSync(path.resolve(__dirname, '../../../public/chain.peg'), 'utf8'); -var PEG = require('pegjs'); -var Parser = PEG.buildParser(grammar); +let fs = require('fs'); +let path = require('path'); +let _ = require('lodash'); +let grammar = fs.readFileSync(path.resolve(__dirname, '../../../public/chain.peg'), 'utf8'); +let PEG = require('pegjs'); +let Parser = PEG.buildParser(grammar); module.exports = function parseSheet(sheet) { return _.map(sheet, function (plot) { try { return Parser.parse(plot).tree; } catch (e) { - var message; + let message; if (e.expected) { throw new Error('Expected: ' + e.expected[0].description + ' @ character ' + e.column); } else { diff --git a/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js b/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js index 178ffaea07873..2e1d1360285bd 100644 --- a/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js +++ b/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function preProcessChainFn(tlConfig) { return function preProcessChain(chain, queries) { queries = queries || {}; function validateAndStore(item) { if (_.isObject(item) && item.type === 'function') { - var functionDef = tlConfig.server.plugins.timelion.getFunction(item.function); + let functionDef = tlConfig.server.plugins.timelion.getFunction(item.function); if (functionDef.datasource) { queries[functionDef.cacheKey(item)] = item; diff --git a/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js b/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js index 23d1b2ddd77c2..ac2a81fc312e9 100644 --- a/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js +++ b/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js @@ -1,21 +1,21 @@ -var _ = require('lodash'); +let _ = require('lodash'); // Applies to unresolved arguments in the AST module.exports = function repositionArguments(functionDef, unorderedArgs) { - var args = []; + let args = []; _.each(unorderedArgs, function (unorderedArg, i) { - var argDef; - var targetIndex; - var value; - var storeAsArray; + let argDef; + let targetIndex; + let value; + let storeAsArray; if (_.isObject(unorderedArg) && unorderedArg.type === 'namedArg') { argDef = functionDef.argsByName[unorderedArg.name]; if (!argDef) { if (functionDef.extended) { - var namesIndex = functionDef.args.length; + let namesIndex = functionDef.args.length; targetIndex = functionDef.args.length + 1; args[namesIndex] = args[namesIndex] || []; diff --git a/src/core_plugins/timelion/server/handlers/lib/tl_config.js b/src/core_plugins/timelion/server/handlers/lib/tl_config.js index f2abeeae1640a..dea23f85b3476 100644 --- a/src/core_plugins/timelion/server/handlers/lib/tl_config.js +++ b/src/core_plugins/timelion/server/handlers/lib/tl_config.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); +let _ = require('lodash'); -var buildTarget = require('../../lib/build_target.js'); +let buildTarget = require('../../lib/build_target.js'); module.exports = function (setup) { - var targetSeries; + let targetSeries; - var tlConfig = { + let tlConfig = { getTargetSeries: function () { return _.map(targetSeries, function (bucket) { // eslint-disable-line no-use-before-define return [bucket, null]; diff --git a/src/core_plugins/timelion/server/handlers/lib/validate_arg.js b/src/core_plugins/timelion/server/handlers/lib/validate_arg.js index cef0b0e22f982..79464b5eaaff6 100644 --- a/src/core_plugins/timelion/server/handlers/lib/validate_arg.js +++ b/src/core_plugins/timelion/server/handlers/lib/validate_arg.js @@ -1,12 +1,12 @@ -var argType = require('./arg_type'); -var _ = require('lodash'); +let argType = require('./arg_type'); +let _ = require('lodash'); module.exports = function (functionDef) { return function validateArg(value, name, argDef) { - var type = argType(value); - var required = argDef.types; - var multi = argDef.multi; - var isCorrectType = (function () { + let type = argType(value); + let required = argDef.types; + let multi = argDef.multi; + let isCorrectType = (function () { // If argument is not allow to be specified multiple times, we're dealing with a plain value for type if (!multi) return _.contains(required, type); // If it is, we'll get an array for type diff --git a/src/core_plugins/timelion/server/handlers/lib/validate_time.js b/src/core_plugins/timelion/server/handlers/lib/validate_time.js index 6268cea94a0ba..284788170feb2 100644 --- a/src/core_plugins/timelion/server/handlers/lib/validate_time.js +++ b/src/core_plugins/timelion/server/handlers/lib/validate_time.js @@ -1,11 +1,11 @@ -var parseDateMath = require('../../lib/date_math.js'); -var toMS = require('../../lib/to_milliseconds.js'); +let parseDateMath = require('../../lib/date_math.js'); +let toMS = require('../../lib/to_milliseconds.js'); module.exports = function validateTime(time, tlConfig) { - var span = parseDateMath(time.to, true) - parseDateMath(time.from); - var interval = toMS(time.interval); - var bucketCount = span / interval; - var maxBuckets = tlConfig.settings['timelion:max_buckets']; + let span = parseDateMath(time.to, true) - parseDateMath(time.from); + let interval = toMS(time.interval); + let bucketCount = span / interval; + let maxBuckets = tlConfig.settings['timelion:max_buckets']; if (bucketCount > maxBuckets) { throw new Error('Max buckets exceeded: ' + Math.round(bucketCount) + ' of ' + maxBuckets + ' allowed. ' + diff --git a/src/core_plugins/timelion/server/lib/__test__/load_functions.js b/src/core_plugins/timelion/server/lib/__test__/load_functions.js index 2e47a36be375d..9f4aaea8124ee 100644 --- a/src/core_plugins/timelion/server/lib/__test__/load_functions.js +++ b/src/core_plugins/timelion/server/lib/__test__/load_functions.js @@ -10,14 +10,14 @@ describe(filename, () => { }); it('returns an object with keys named for the javascript files in the directory', () => { - var fnList = fn('series_functions'); + let fnList = fn('series_functions'); expect(fnList).to.be.an('object'); expect(fnList.sum).to.be.a('object'); }); it('also includes index.js files in direct subdirectories, and names the keys for the directory', () => { - var fnList = fn('series_functions'); + let fnList = fn('series_functions'); expect(fnList).to.be.an('object'); expect(fnList.es).to.be.a('object'); diff --git a/src/core_plugins/timelion/server/lib/alter.js b/src/core_plugins/timelion/server/lib/alter.js index bdc68875c698e..3168ccfbe29cc 100644 --- a/src/core_plugins/timelion/server/lib/alter.js +++ b/src/core_plugins/timelion/server/lib/alter.js @@ -1,5 +1,5 @@ -var Promise = require('bluebird'); -var _ = require('lodash'); +let Promise = require('bluebird'); +let _ = require('lodash'); /* @param {Array} args * - args[0] must be a seriesList @@ -12,13 +12,13 @@ module.exports = function alter(args, fn) { // In theory none of the args should ever be promises. This is probably a waste. return Promise.all(args).then(function (args) { - var seriesList = args.shift(); + let seriesList = args.shift(); if (seriesList.type !== 'seriesList') { throw new Error ('args[0] must be a seriesList'); } - var list = _.chain(seriesList.list).map(function (series) { + let list = _.chain(seriesList.list).map(function (series) { return fn.apply(this, [series].concat(args)); }).flatten().value(); diff --git a/src/core_plugins/timelion/server/lib/asSorted.js b/src/core_plugins/timelion/server/lib/asSorted.js index 914797a6e3cb2..b7ae85b36278f 100644 --- a/src/core_plugins/timelion/server/lib/asSorted.js +++ b/src/core_plugins/timelion/server/lib/asSorted.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); -var unzipPairs = require('./unzipPairs.js'); +let _ = require('lodash'); +let unzipPairs = require('./unzipPairs.js'); module.exports = function asSorted(timeValObject, fn) { - var data = unzipPairs(timeValObject); + let data = unzipPairs(timeValObject); return _.zipObject(fn(data)); }; diff --git a/src/core_plugins/timelion/server/lib/build_target.js b/src/core_plugins/timelion/server/lib/build_target.js index 14c8bbc20711d..af23589edf7e9 100644 --- a/src/core_plugins/timelion/server/lib/build_target.js +++ b/src/core_plugins/timelion/server/lib/build_target.js @@ -1,16 +1,16 @@ -var moment = require('moment'); +let moment = require('moment'); -var splitInterval = require('./split_interval.js'); +let splitInterval = require('./split_interval.js'); module.exports = function (tlConfig) { - var min = moment(tlConfig.time.from); - var max = moment(tlConfig.time.to); + let min = moment(tlConfig.time.from); + let max = moment(tlConfig.time.to); - var intervalParts = splitInterval(tlConfig.time.interval); + let intervalParts = splitInterval(tlConfig.time.interval); - var current = min.startOf(intervalParts.unit); + let current = min.startOf(intervalParts.unit); - var targetSeries = []; + let targetSeries = []; while (current.valueOf() < max.valueOf()) { targetSeries.push(current.valueOf()); diff --git a/src/core_plugins/timelion/server/lib/classes/chainable.js b/src/core_plugins/timelion/server/lib/classes/chainable.js index 1b8914e163a89..7b8c7fe136168 100644 --- a/src/core_plugins/timelion/server/lib/classes/chainable.js +++ b/src/core_plugins/timelion/server/lib/classes/chainable.js @@ -1,4 +1,4 @@ -var TimelionFunction = require('./timelion_function'); +let TimelionFunction = require('./timelion_function'); module.exports = class Chainable extends TimelionFunction { constructor(name, config) { diff --git a/src/core_plugins/timelion/server/lib/classes/datasource.js b/src/core_plugins/timelion/server/lib/classes/datasource.js index 5f9cf820980ff..8b64e9eb58c64 100644 --- a/src/core_plugins/timelion/server/lib/classes/datasource.js +++ b/src/core_plugins/timelion/server/lib/classes/datasource.js @@ -1,10 +1,10 @@ -var loadFunctions = require('../load_functions.js'); -var fitFunctions = loadFunctions('fit_functions'); -var TimelionFunction = require('./timelion_function'); -var offsetTime = require('../offset_time'); +let loadFunctions = require('../load_functions.js'); +let fitFunctions = loadFunctions('fit_functions'); +let TimelionFunction = require('./timelion_function'); +let offsetTime = require('../offset_time'); -var _ = require('lodash'); -var moment = require('moment'); +let _ = require('lodash'); +let moment = require('moment'); function offsetSeries(response, offset) { @@ -33,9 +33,9 @@ module.exports = class Datasource extends TimelionFunction { }); // Wrap the original function so we can modify inputs/outputs with offset & fit - var originalFunction = config.fn; + let originalFunction = config.fn; config.fn = function (args, tlConfig) { - var config = _.clone(tlConfig); + let config = _.clone(tlConfig); if (args.byName.offset) { config.time = _.cloneDeep(tlConfig.time); config.time.from = offsetTime(config.time.from, args.byName.offset); diff --git a/src/core_plugins/timelion/server/lib/classes/timelion_function.js b/src/core_plugins/timelion/server/lib/classes/timelion_function.js index 10f0e9ea6fc7b..96dc49c619b7a 100644 --- a/src/core_plugins/timelion/server/lib/classes/timelion_function.js +++ b/src/core_plugins/timelion/server/lib/classes/timelion_function.js @@ -1,6 +1,6 @@ -var _ = require('lodash'); -var loadFunctions = require('../load_functions.js'); -var fitFunctions = loadFunctions('fit_functions'); +let _ = require('lodash'); +let loadFunctions = require('../load_functions.js'); +let fitFunctions = loadFunctions('fit_functions'); module.exports = class TimelionFunction { constructor(name, config) { @@ -12,21 +12,21 @@ module.exports = class TimelionFunction { this.extended = config.extended || false; // WTF is this? How could you not have a fn? Wtf would the thing be used for? - var originalFunction = config.fn || function (input) { return input; }; + let originalFunction = config.fn || function (input) { return input; }; // Currently only re-fits the series. this.originalFn = originalFunction; this.fn = function (args, tlConfig) { - var config = _.clone(tlConfig); + let config = _.clone(tlConfig); return Promise.resolve(originalFunction(args, config)).then(function (seriesList) { seriesList.list = _.map(seriesList.list, function (series) { - var target = tlConfig.getTargetSeries(); + let target = tlConfig.getTargetSeries(); // Don't fit if the series are already the same if (_.isEqual(_.map(series.data, 0), _.map(target, 0))) return series; - var fit; + let fit; if (args.byName.fit) { fit = args.byName.fit; } else if (series.fit) { diff --git a/src/core_plugins/timelion/server/lib/date_math.js b/src/core_plugins/timelion/server/lib/date_math.js index c57651b59018f..6ae0f998e5eca 100644 --- a/src/core_plugins/timelion/server/lib/date_math.js +++ b/src/core_plugins/timelion/server/lib/date_math.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); -var moment = require('moment'); +let _ = require('lodash'); +let moment = require('moment'); -var units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; +let units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; /* This is a simplified version of elasticsearch's date parser */ function parse(text, roundUp) { @@ -15,10 +15,10 @@ function parse(text, roundUp) { return moment(text); } - var time; - var mathString = ''; - var index; - var parseString; + let time; + let mathString = ''; + let index; + let parseString; if (text.substring(0, 3) === 'now') { time = moment(); @@ -44,13 +44,13 @@ function parse(text, roundUp) { } function parseDateMath(mathString, time, roundUp) { - var dateTime = time; + let dateTime = time; - for (var i = 0; i < mathString.length;) { - var c = mathString.charAt(i++); - var type; - var num; - var unit; + for (let i = 0; i < mathString.length;) { + let c = mathString.charAt(i++); + let type; + let num; + let unit; if (c === '/') { type = 0; @@ -67,7 +67,7 @@ function parseDateMath(mathString, time, roundUp) { } else if (mathString.length === 2) { num = mathString.charAt(i); } else { - var numFrom = i; + let numFrom = i; while (!isNaN(mathString.charAt(i))) { i++; if (i > 10) { diff --git a/src/core_plugins/timelion/server/lib/functions_md.js b/src/core_plugins/timelion/server/lib/functions_md.js index 15300fa1e19ce..93056c13199fc 100644 --- a/src/core_plugins/timelion/server/lib/functions_md.js +++ b/src/core_plugins/timelion/server/lib/functions_md.js @@ -1,16 +1,16 @@ -var loadFunctions = require('./load_functions.js'); -var functions = loadFunctions('series_functions/'); -var _ = require('lodash'); +let loadFunctions = require('./load_functions.js'); +let functions = loadFunctions('series_functions/'); +let _ = require('lodash'); module.exports = (function () { - var functionArray = _.map(functions, function (val, key) { + let functionArray = _.map(functions, function (val, key) { // TODO: This won't work on frozen objects, it should be removed when everything is converted to datasources and chainables return _.extend({}, val, {name: key}); }); function toDocBlock(fn) { - var help = ''; + let help = ''; if (fn.isAlias) return help; @@ -18,7 +18,7 @@ module.exports = (function () { help += fn.help + '\n\n'; // If chainable, drop first argument from help - var args = fn.chainable ? fn.args.slice(1) : fn.args.slice(); + let args = fn.chainable ? fn.args.slice(1) : fn.args.slice(); if (!args.length) { help += '*This function does not accept any arguments.*\n\n'; return help; @@ -39,7 +39,7 @@ module.exports = (function () { } function createDocs() { - var help = ''; + let help = ''; help += '## Timelion function reference\n'; help += 'This document is auto generated from the timelion code. ' + 'Do not submit pulls against this document. You want to submit a pull against something in the ' + diff --git a/src/core_plugins/timelion/server/lib/get_namespaced_settings.js b/src/core_plugins/timelion/server/lib/get_namespaced_settings.js index 705baff04270d..dd10ac30c456e 100644 --- a/src/core_plugins/timelion/server/lib/get_namespaced_settings.js +++ b/src/core_plugins/timelion/server/lib/get_namespaced_settings.js @@ -1,5 +1,5 @@ -var _ = require('lodash'); -var configFile = require('../../timelion.json'); +let _ = require('lodash'); +let configFile = require('../../timelion.json'); module.exports = function () { function flattenWith(dot, nestedObj, flattenArrays) { @@ -17,7 +17,7 @@ module.exports = function () { return flatObj; }; - var timelionDefaults = flattenWith('.', configFile); + let timelionDefaults = flattenWith('.', configFile); return _.reduce(timelionDefaults, (result, value, key) => { result['timelion:' + key] = value; return result; diff --git a/src/core_plugins/timelion/server/lib/load_functions.js b/src/core_plugins/timelion/server/lib/load_functions.js index 3bb0ecee7ae25..bb9e905c75b99 100644 --- a/src/core_plugins/timelion/server/lib/load_functions.js +++ b/src/core_plugins/timelion/server/lib/load_functions.js @@ -1,33 +1,33 @@ -var _ = require('lodash'); -var glob = require('glob'); -var path = require('path'); -var processFunctionDefinition = require('./process_function_definition'); +let _ = require('lodash'); +let glob = require('glob'); +let path = require('path'); +let processFunctionDefinition = require('./process_function_definition'); module.exports = function (directory) { function getTuple(directory, name) { - var func = require('../' + directory + '/' + name); + let func = require('../' + directory + '/' + name); return [name, require('../' + directory + '/' + name)]; } // Get a list of all files and use the filename as the object key - var files = _.map(glob.sync(path.resolve(__dirname, '../' + directory + '/*.js')), function (file) { - var name = file.substring(file.lastIndexOf('/') + 1, file.lastIndexOf('.')); + let files = _.map(glob.sync(path.resolve(__dirname, '../' + directory + '/*.js')), function (file) { + let name = file.substring(file.lastIndexOf('/') + 1, file.lastIndexOf('.')); return getTuple(directory, name); }); // Get a list of all directories with an index.js, use the directory name as the key in the object - var directories = _.chain(glob.sync(path.resolve(__dirname, '../' + directory + '/*/index.js'))) + let directories = _.chain(glob.sync(path.resolve(__dirname, '../' + directory + '/*/index.js'))) .filter(function (file) { return file.match(/__test__/) == null; }) .map(function (file) { - var parts = file.split('/'); - var name = parts[parts.length - 2]; + let parts = file.split('/'); + let name = parts[parts.length - 2]; return getTuple(directory, parts[parts.length - 2]); }).value(); - var functions = _.zipObject(files.concat(directories)); + let functions = _.zipObject(files.concat(directories)); _.each(functions, function (func) { _.assign(functions, processFunctionDefinition(func)); diff --git a/src/core_plugins/timelion/server/lib/offset_time.js b/src/core_plugins/timelion/server/lib/offset_time.js index 84dc5cd68830a..c22d824acc88f 100644 --- a/src/core_plugins/timelion/server/lib/offset_time.js +++ b/src/core_plugins/timelion/server/lib/offset_time.js @@ -1,17 +1,17 @@ -var moment = require('moment'); +let moment = require('moment'); // usually reverse = false on the request, true on the response module.exports = function offsetTime(milliseconds, offset, reverse) { if (!offset.match(/[-+][0-9]+[mshdwMy]/g)) { throw new Error ('Malformed `offset` at ' + offset); } - var parts = offset.match(/[-+]|[0-9]+|[mshdwMy]/g); + let parts = offset.match(/[-+]|[0-9]+|[mshdwMy]/g); - var add = parts[0] === '+'; + let add = parts[0] === '+'; add = reverse ? !add : add; - var mode = add ? 'add' : 'subtract'; + let mode = add ? 'add' : 'subtract'; - var momentObj = moment(milliseconds)[mode](parts[1], parts[2]); + let momentObj = moment(milliseconds)[mode](parts[1], parts[2]); return momentObj.valueOf(); }; diff --git a/src/core_plugins/timelion/server/lib/process_function_definition.js b/src/core_plugins/timelion/server/lib/process_function_definition.js index 0e17cb7a39692..8afe0ab276d10 100644 --- a/src/core_plugins/timelion/server/lib/process_function_definition.js +++ b/src/core_plugins/timelion/server/lib/process_function_definition.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function (func) { - var functions = {}; + let functions = {}; functions[func.name] = func; if (func.aliases) { _.each(func.aliases, function (alias) { - var aliasFn = _.clone(func); + let aliasFn = _.clone(func); aliasFn.isAlias = true; functions[alias] = aliasFn; }); diff --git a/src/core_plugins/timelion/server/lib/reduce.js b/src/core_plugins/timelion/server/lib/reduce.js index bdb420799ba48..53971f2a11720 100644 --- a/src/core_plugins/timelion/server/lib/reduce.js +++ b/src/core_plugins/timelion/server/lib/reduce.js @@ -1,5 +1,5 @@ -var _ = require('lodash'); -var Promise = require('bluebird'); +let _ = require('lodash'); +let Promise = require('bluebird'); /** @@ -15,8 +15,8 @@ var Promise = require('bluebird'); module.exports = function reduce(args, fn) { return Promise.all(args).then(function (args) { - var seriesList = args.shift(); - var argument = args.shift(); + let seriesList = args.shift(); + let argument = args.shift(); if (seriesList.type !== 'seriesList') { throw new Error ('input must be a seriesList'); @@ -34,9 +34,9 @@ module.exports = function reduce(args, fn) { function reduceSeries(series) { return _.reduce(series, function (destinationObject, argument, i, p) { - var output = _.map(destinationObject.data, function (point, index) { + let output = _.map(destinationObject.data, function (point, index) { - var value = point[1]; + let value = point[1]; if (value == null) { return [point[0], null]; @@ -64,7 +64,7 @@ module.exports = function reduce(args, fn) { } - var reduced; + let reduced; if (argument != null) { reduced = _.map(seriesList.list, function (series) { diff --git a/src/core_plugins/timelion/server/lib/split_interval.js b/src/core_plugins/timelion/server/lib/split_interval.js index d19ce50fac89f..11ad0f9239b30 100644 --- a/src/core_plugins/timelion/server/lib/split_interval.js +++ b/src/core_plugins/timelion/server/lib/split_interval.js @@ -2,7 +2,7 @@ module.exports = function splitInterval(interval) { if (!interval.match(/[0-9]+[mshdwMy]+/g)) { throw new Error ('Malformed `interval`: ' + interval); } - var parts = interval.match(/[0-9]+|[mshdwMy]+/g); + let parts = interval.match(/[0-9]+|[mshdwMy]+/g); return { count: parts[0], diff --git a/src/core_plugins/timelion/server/lib/to_milliseconds.js b/src/core_plugins/timelion/server/lib/to_milliseconds.js index c109749ea1f2f..17318017fd8fb 100644 --- a/src/core_plugins/timelion/server/lib/to_milliseconds.js +++ b/src/core_plugins/timelion/server/lib/to_milliseconds.js @@ -1,9 +1,9 @@ -var _ = require('lodash'); -var moment = require('moment'); +let _ = require('lodash'); +let moment = require('moment'); // map of moment's short/long unit ids and elasticsearch's long unit ids // to their value in milliseconds -var vals = _.transform([ +let vals = _.transform([ ['ms', 'milliseconds', 'millisecond'], ['s', 'seconds', 'second', 'sec'], ['m', 'minutes', 'minute', 'min'], @@ -14,17 +14,17 @@ var vals = _.transform([ ['quarter'], ['y', 'years', 'year'] ], function (vals, units) { - var normal = moment.normalizeUnits(units[0]); - var val = moment.duration(1, normal).asMilliseconds(); + let normal = moment.normalizeUnits(units[0]); + let val = moment.duration(1, normal).asMilliseconds(); [].concat(normal, units).forEach(function (unit) { vals[unit] = val; }); }, {}); // match any key from the vals object prececed by an optional number -var parseRE = new RegExp('^(\\d+(?:\\.\\d*)?)?\\s*(' + _.keys(vals).join('|') + ')$'); +let parseRE = new RegExp('^(\\d+(?:\\.\\d*)?)?\\s*(' + _.keys(vals).join('|') + ')$'); module.exports = function (expr) { - var match = expr.match(parseRE); + let match = expr.match(parseRE); if (match) { if (match[2] === 'M' && match[1] !== '1') { throw new Error ('Invalid interval. 1M is only valid monthly interval.'); diff --git a/src/core_plugins/timelion/server/lib/unzipPairs.js b/src/core_plugins/timelion/server/lib/unzipPairs.js index 88f1510d29c49..71b4ddefb3aa9 100644 --- a/src/core_plugins/timelion/server/lib/unzipPairs.js +++ b/src/core_plugins/timelion/server/lib/unzipPairs.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function unzipPairs(timeValObject) { - var paired = _.chain(timeValObject).pairs().map(function (point) { + let paired = _.chain(timeValObject).pairs().map(function (point) { return [parseInt(point[0], 10), point[1]]; }).sortBy(function (point) { return point[0]; diff --git a/src/core_plugins/timelion/server/routes/functions.js b/src/core_plugins/timelion/server/routes/functions.js index 93dca0ec034ca..60227ecd79147 100644 --- a/src/core_plugins/timelion/server/routes/functions.js +++ b/src/core_plugins/timelion/server/routes/functions.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function (server) { server.route({ method: 'GET', path: '/api/timelion/functions', handler: function (request, reply) { - var functionArray = _.map(server.plugins.timelion.functions, function (val, key) { + let functionArray = _.map(server.plugins.timelion.functions, function (val, key) { // TODO: This won't work on frozen objects, it should be removed when everything is converted to datasources and chainables return _.extend({}, val, {name: key}); }); diff --git a/src/core_plugins/timelion/server/routes/run.js b/src/core_plugins/timelion/server/routes/run.js index 0855b2384959c..e6192de69de89 100644 --- a/src/core_plugins/timelion/server/routes/run.js +++ b/src/core_plugins/timelion/server/routes/run.js @@ -1,8 +1,8 @@ -var Promise = require('bluebird'); -var _ = require('lodash'); -var Boom = require('boom'); -var chainRunnerFn = require('../handlers/chain_runner.js'); -var timelionDefaults = require('../lib/get_namespaced_settings')(); +let Promise = require('bluebird'); +let _ = require('lodash'); +let Boom = require('boom'); +let chainRunnerFn = require('../handlers/chain_runner.js'); +let timelionDefaults = require('../lib/get_namespaced_settings')(); function replyWithError(e, reply) { reply({title: e.toString(), message: e.toString(), stack: e.stack}).code(400); @@ -20,13 +20,13 @@ module.exports = (server) => { // before every request. This just sucks because its going to slow things // down. Meh. return server.uiSettings().getAll().then((uiSettings) => { - var sheet; - var tlConfig = require('../handlers/lib/tl_config.js')({ + let sheet; + let tlConfig = require('../handlers/lib/tl_config.js')({ server: server, request: request, settings: _.defaults(uiSettings, timelionDefaults) // Just in case they delete some setting. }); - var chainRunner = chainRunnerFn(tlConfig); + let chainRunner = chainRunnerFn(tlConfig); try { sheet = chainRunner.processRequest(request.payload || { @@ -44,7 +44,7 @@ module.exports = (server) => { } return Promise.all(sheet).then((sheet) => { - var response = { + let response = { sheet: sheet, stats: chainRunner.getStats() }; diff --git a/src/core_plugins/timelion/server/routes/validate_es.js b/src/core_plugins/timelion/server/routes/validate_es.js index 482c2fdac4d07..4fab86a251257 100644 --- a/src/core_plugins/timelion/server/routes/validate_es.js +++ b/src/core_plugins/timelion/server/routes/validate_es.js @@ -5,11 +5,11 @@ module.exports = function (server) { handler: function (request, reply) { return server.uiSettings().getAll().then((uiSettings) => { - var callWithRequest = server.plugins.elasticsearch.callWithRequest; + let callWithRequest = server.plugins.elasticsearch.callWithRequest; - var timefield = uiSettings['timelion:es.timefield']; + let timefield = uiSettings['timelion:es.timefield']; - var body = { + let body = { index: uiSettings['es.default_index'], fields:timefield }; diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/abs.js b/src/core_plugins/timelion/server/series_functions/__tests__/abs.js index a9b10c1aa13a7..a13676b49abd8 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/abs.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/abs.js @@ -1,20 +1,20 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); -var _ = require('lodash'); -var expect = require('chai').expect; -var seriesList = require('./fixtures/seriesList.js')(); -var invoke = require('./helpers/invoke_series_fn.js'); +let _ = require('lodash'); +let expect = require('chai').expect; +let seriesList = require('./fixtures/seriesList.js')(); +let invoke = require('./helpers/invoke_series_fn.js'); describe(filename, function () { it('should return the positive value of every value', function () { return invoke(fn, [seriesList]).then(function (result) { - var before = _.filter(result.input[0].list[0].data, function (point) { + let before = _.filter(result.input[0].list[0].data, function (point) { return (point[1] < 0); }); - var after = _.filter(result.output.list[0].data, function (point) { + let after = _.filter(result.output.list[0].data, function (point) { return (point[1] < 0); }); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/bars.js b/src/core_plugins/timelion/server/series_functions/__tests__/bars.js index fc3156ed08047..ea6c79cae8d22 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/bars.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/bars.js @@ -1,20 +1,20 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); -var _ = require('lodash'); -var expect = require('chai').expect; -var invoke = require('./helpers/invoke_series_fn.js'); +let _ = require('lodash'); +let expect = require('chai').expect; +let invoke = require('./helpers/invoke_series_fn.js'); describe(filename, () => { - var seriesList; + let seriesList; beforeEach(() => { seriesList = require('./fixtures/seriesList.js')(); }); it('creates the bars property, with defaults, on all series', () => { return invoke(fn, [seriesList]).then((r) => { - var bars = _.map(r.output.list, 'bars'); + let bars = _.map(r.output.list, 'bars'); _.each(bars, (bar) => expect(bar).to.be.a('object')); _.each(bars, (bar) => expect(bar.lineWidth).to.equal(6)); _.each(bars, (bar) => expect(bar.show).to.equal(1)); @@ -24,7 +24,7 @@ describe(filename, () => { it('leaves existing bars alone when called without option, if they exist', () => { seriesList.list[0].bars = {foo: true}; return invoke(fn, [seriesList]).then((r) => { - var bars = _.map(r.output.list, 'bars'); + let bars = _.map(r.output.list, 'bars'); expect(bars[0].foo).to.equal(true); expect(bars[1].foo).to.equal(undefined); }); @@ -32,7 +32,7 @@ describe(filename, () => { it('sets lineWidth and show to the same value', () => { return invoke(fn, [seriesList, 0]).then((r) => { - var bars = _.map(r.output.list, 'bars'); + let bars = _.map(r.output.list, 'bars'); expect(bars[0].lineWidth).to.equal(0); expect(bars[0].show).to.equal(0); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/condition.js b/src/core_plugins/timelion/server/series_functions/__tests__/condition.js index 21c696a8f0072..6df056d23e4f0 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/condition.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/condition.js @@ -1,15 +1,15 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); -var moment = require('moment'); -var expect = require('chai').expect; -var invoke = require('./helpers/invoke_series_fn.js'); -var getSeriesList = require('./helpers/get_single_series_list'); -var _ = require('lodash'); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); +let moment = require('moment'); +let expect = require('chai').expect; +let invoke = require('./helpers/invoke_series_fn.js'); +let getSeriesList = require('./helpers/get_single_series_list'); +let _ = require('lodash'); describe(filename, function () { - var comparable; - var seriesList; + let comparable; + let seriesList; beforeEach(function () { seriesList = require('./fixtures/seriesList.js')(); comparable = getSeriesList('',[ diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/es.js b/src/core_plugins/timelion/server/series_functions/__tests__/es.js index 6e227b49889e5..e2ea4d9cb20dd 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/es.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/es.js @@ -25,7 +25,7 @@ function stubResponse(response) { } describe(filename, () => { - var tlConfig; + let tlConfig; describe('seriesList processor', () => { it('throws an error then the index is missing', () => { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/first.js b/src/core_plugins/timelion/server/series_functions/__tests__/first.js index febe0a47e7890..67c40cda8bab4 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/first.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/first.js @@ -1,9 +1,9 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); -var expect = require('chai').expect; -var seriesList = require('./fixtures/seriesList.js')(); -var invoke = require('./helpers/invoke_series_fn.js'); +let expect = require('chai').expect; +let seriesList = require('./fixtures/seriesList.js')(); +let invoke = require('./helpers/invoke_series_fn.js'); describe(filename, function () { it('should return exactly the data input', function () { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fit.js b/src/core_plugins/timelion/server/series_functions/__tests__/fit.js index 6caba53691183..c181f8c53355d 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fit.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fit.js @@ -1,16 +1,16 @@ -var filename = require('path').basename(__filename); -var fn = require(`../${filename}`); -var moment = require('moment'); -var expect = require('chai').expect; -var invoke = require('./helpers/invoke_series_fn.js'); -var getSeriesList = require('./helpers/get_single_series_list'); -var _ = require('lodash'); +let filename = require('path').basename(__filename); +let fn = require(`../${filename}`); +let moment = require('moment'); +let expect = require('chai').expect; +let invoke = require('./helpers/invoke_series_fn.js'); +let getSeriesList = require('./helpers/get_single_series_list'); +let _ = require('lodash'); describe(filename, function () { describe('carry', function () { it('should maintain the previous value until it changes', function () { - var seriesList = getSeriesList('',[ + let seriesList = getSeriesList('',[ [moment.utc('1980-01-01T00:00:00.000Z'), 5], [moment.utc('1981-01-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), 3.4], @@ -27,7 +27,7 @@ describe(filename, function () { describe('nearest', function () { it('should use the closest temporal value to fill the null', function () { - var seriesList = getSeriesList('',[ + let seriesList = getSeriesList('',[ [moment.utc('1980-01-01T00:00:00.000Z'), 5], [moment.utc('1981-01-01T00:00:00.000Z'), null], [moment.utc('1981-05-01T00:00:00.000Z'), 3.4], @@ -46,7 +46,7 @@ describe(filename, function () { describe('average', function () { it('should produce a smooth, straight line between points', function () { - var seriesList = getSeriesList('',[ + let seriesList = getSeriesList('',[ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), null], @@ -64,7 +64,7 @@ describe(filename, function () { describe('scale', function () { it('should distribute the next points value across the preceeding nulls', function () { - var seriesList = getSeriesList('', [ + let seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), null], @@ -80,7 +80,7 @@ describe(filename, function () { describe('none', function () { it('basically just drops the nulls. This is going to screw you', function () { - var seriesList = getSeriesList('', [ + let seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), null], diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js index 04cdc0f3f47c6..37c08ebfe2d82 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js @@ -1,4 +1,4 @@ -var moment = require('moment'); +let moment = require('moment'); module.exports = [ moment('1980-01-01T00:00:00.000Z'), diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js index 9d094541d2195..0f814c98aeb62 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js @@ -1,8 +1,8 @@ -var Promise = require('bluebird'); -var buckets = require('./bucketList'); -var getSeries = require('../helpers/get_series'); -var getSeriesList = require('../helpers/get_series_list'); -var _ = require('lodash'); +let Promise = require('bluebird'); +let buckets = require('./bucketList'); +let getSeries = require('../helpers/get_series'); +let getSeriesList = require('../helpers/get_series_list'); +let _ = require('lodash'); module.exports = function () { return getSeriesList([ diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js index 586c7e3b7b981..e83b25b051ddc 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js @@ -1,8 +1,8 @@ -var moment = require('moment'); -var timelionDefaults = require('../../../lib/get_namespaced_settings'); +let moment = require('moment'); +let timelionDefaults = require('../../../lib/get_namespaced_settings'); module.exports = function () { - var tlConfig = require('../../../handlers/lib/tl_config.js')({ + let tlConfig = require('../../../handlers/lib/tl_config.js')({ server: {}, request: {} }); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js b/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js index 8bdb12e446c86..55df757305334 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js @@ -1,9 +1,9 @@ -var proxyquire = require('proxyquire'); -var Promise = require('bluebird'); -var _ = require('lodash'); -var expect = require('chai').expect; +let proxyquire = require('proxyquire'); +let Promise = require('bluebird'); +let _ = require('lodash'); +let expect = require('chai').expect; -var graphiteResponse = function (url) { +let graphiteResponse = function (url) { return Promise.resolve({ json: function () { return [{ @@ -19,10 +19,10 @@ var graphiteResponse = function (url) { }); }; -var filename = require('path').basename(__filename); -var fn = proxyquire(`../${filename}`, {'node-fetch': graphiteResponse}); +let filename = require('path').basename(__filename); +let fn = proxyquire(`../${filename}`, {'node-fetch': graphiteResponse}); -var invoke = require('./helpers/invoke_series_fn.js'); +let invoke = require('./helpers/invoke_series_fn.js'); describe(filename, function () { it('should wrap the graphite response up in a seriesList', function () { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js index 7f8268793f685..3cb52252e7bfe 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function getSeries(name, buckets, points) { - var fill = _.partial(_.zip, _.map(buckets, function (bucket) { return bucket.valueOf(); })); + let fill = _.partial(_.zip, _.map(buckets, function (bucket) { return bucket.valueOf(); })); return { data: fill(points), type: 'series', diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js index a55d824a09c31..439886963e62e 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js @@ -1,4 +1,4 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function (list, overrides) { return _.merge({ diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js index aef77fb0a646a..5ace294cc16b3 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js @@ -1,6 +1,6 @@ -var getSeries = require('../helpers/get_series'); -var getSeriesList = require('../helpers/get_series_list'); -var _ = require('lodash'); +let getSeries = require('../helpers/get_series'); +let getSeriesList = require('../helpers/get_series_list'); +let _ = require('lodash'); module.exports = function (name, data) { return getSeriesList([getSeries(name, _.map(data, 0), _.map(data, 1))]); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js index 1e4ff72e52ddf..573b2df62d5aa 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js @@ -1,18 +1,18 @@ // invokes a series_function with the specified arguments -var _ = require('lodash'); -var indexArguments = require('../../../handlers/lib/index_arguments'); +let _ = require('lodash'); +let indexArguments = require('../../../handlers/lib/index_arguments'); module.exports = function invokeSeriesFn(fnDef, args, tlConfigOverrides) { - var tlConfig = _.merge(require('../fixtures/tlConfig')(), tlConfigOverrides); + let tlConfig = _.merge(require('../fixtures/tlConfig')(), tlConfigOverrides); return Promise.all(args).then(function (args) { args.byName = indexArguments(fnDef, args); - var input = _.cloneDeep(args); + let input = _.cloneDeep(args); return Promise.resolve(fnDef.originalFn(args, tlConfig)).then(function (output) { - var result = { + let result = { output: output, input: input }; diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js b/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js index f3d29f2a4e7a3..345b50331074b 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js @@ -14,7 +14,7 @@ describe(filename, () => { it('computes the moving standard deviation of a list', () => { return invoke(fn, [seriesList, 2]).then((r) => { - var values = _.map(r.output.list[1].data, 1); + let values = _.map(r.output.list[1].data, 1); expect(values[0]).to.equal(null); expect(values[1]).to.equal(null); expect(values[2]).to.be.within(26, 27); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/points.js b/src/core_plugins/timelion/server/series_functions/__tests__/points.js index 2f3155742b8bf..3918d752bc13f 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/points.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/points.js @@ -44,7 +44,7 @@ describe(filename, () => { }); describe('symbol', () => { - var symbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; + let symbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; _.each(symbols, (symbol) => { it(`is ${symbol}`, () => { return invoke(fn, [seriesList, null, null, null, null, symbol]).then((r) => { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js b/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js index b191f594b041b..9e01408c1c423 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js @@ -1,20 +1,20 @@ -var proxyquire = require('proxyquire'); -var Promise = require('bluebird'); -var _ = require('lodash'); +let proxyquire = require('proxyquire'); +let Promise = require('bluebird'); +let _ = require('lodash'); const assert = require('chai'); const expect = assert.expect; -var parseURL = require('url').parse; -var parseQueryString = require('querystring').parse; -var tlConfig = require('./fixtures/tlConfig')(); -var moment = require('moment'); +let parseURL = require('url').parse; +let parseQueryString = require('querystring').parse; +let tlConfig = require('./fixtures/tlConfig')(); +let moment = require('moment'); -var filename = require('path').basename(__filename); -var invoke = require('./helpers/invoke_series_fn.js'); +let filename = require('path').basename(__filename); +let invoke = require('./helpers/invoke_series_fn.js'); -var fn; -var response; -var calledWith; +let fn; +let response; +let calledWith; describe(filename, function () { beforeEach(function () { diff --git a/src/core_plugins/timelion/server/series_functions/abs.js b/src/core_plugins/timelion/server/series_functions/abs.js index e05fc0dcd0087..6f1ac19665028 100644 --- a/src/core_plugins/timelion/server/series_functions/abs.js +++ b/src/core_plugins/timelion/server/series_functions/abs.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('abs', { args: [ { @@ -11,7 +11,7 @@ module.exports = new Chainable('abs', { help: 'Return the absolute value of each value in the series list', fn: function absFn(args) { return alter(args, function (eachSeries) { - var data = _.map(eachSeries.data, function (point) { + let data = _.map(eachSeries.data, function (point) { return [point[0], Math.abs(point[1])]; }); eachSeries.data = data; diff --git a/src/core_plugins/timelion/server/series_functions/bars.js b/src/core_plugins/timelion/server/series_functions/bars.js index f2600d95077a1..3a1ed374ac614 100644 --- a/src/core_plugins/timelion/server/series_functions/bars.js +++ b/src/core_plugins/timelion/server/series_functions/bars.js @@ -1,5 +1,5 @@ -var alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('bars', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/color.js b/src/core_plugins/timelion/server/series_functions/color.js index 0aa65431b1871..39318c78ef753 100644 --- a/src/core_plugins/timelion/server/series_functions/color.js +++ b/src/core_plugins/timelion/server/series_functions/color.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); -var tinygradient = require('tinygradient'); +let alter = require('../lib/alter.js'); +let Chainable = require('../lib/classes/chainable'); +let tinygradient = require('tinygradient'); module.exports = new Chainable('color', { args: [ @@ -17,13 +17,13 @@ module.exports = new Chainable('color', { ], help: 'Change the color of the series', fn: function colorFn(args) { - var colors = args.byName.color.split(':'); + let colors = args.byName.color.split(':'); if (colors.length > 1 && args.byName.inputSeries.list.length > 1) { colors = tinygradient(colors).rgb(args.byName.inputSeries.list.length); } - var i = 0; + let i = 0; return alter(args, function (eachSeries) { if (colors.length === 1 || args.byName.inputSeries.list.length === 1) { eachSeries.color = colors[0]; diff --git a/src/core_plugins/timelion/server/series_functions/condition.js b/src/core_plugins/timelion/server/series_functions/condition.js index 5907ab972dc48..64323e89a8fdf 100644 --- a/src/core_plugins/timelion/server/series_functions/condition.js +++ b/src/core_plugins/timelion/server/series_functions/condition.js @@ -1,7 +1,7 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); -var argType = require('../handlers/lib/arg_type.js'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); +let argType = require('../handlers/lib/arg_type.js'); module.exports = new Chainable('condition', { args: [ @@ -35,9 +35,9 @@ module.exports = new Chainable('condition', { 'to the result if the condition proves true, with an optional else.', aliases: ['if'], fn: function conditionFn(args) { - var config = args.byName; + let config = args.byName; return alter(args, function (eachSeries) { - var data = _.map(eachSeries.data, function (point, i) { + let data = _.map(eachSeries.data, function (point, i) { function getNumber(source) { if (argType(source) === 'number') return source; if (argType(source) === 'null') return null; @@ -45,11 +45,11 @@ module.exports = new Chainable('condition', { throw new Error ('must be a number or a seriesList'); } - var ifVal = getNumber(config.if); - var thenVal = getNumber(config.then); - var elseVal = _.isUndefined(config.else) ? point[1] : getNumber(config.else); + let ifVal = getNumber(config.if); + let thenVal = getNumber(config.then); + let elseVal = _.isUndefined(config.else) ? point[1] : getNumber(config.else); - var newValue = (function () { + let newValue = (function () { switch (config.operator) { case 'lt': return point[1] < ifVal ? thenVal : elseVal; diff --git a/src/core_plugins/timelion/server/series_functions/cusum.js b/src/core_plugins/timelion/server/series_functions/cusum.js index 454e11ae73852..058f0545c6cf3 100644 --- a/src/core_plugins/timelion/server/series_functions/cusum.js +++ b/src/core_plugins/timelion/server/series_functions/cusum.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('cusum', { args: [ { @@ -16,8 +16,8 @@ module.exports = new Chainable('cusum', { help: 'Return the cumulative sum of a series, starting at a base.', fn: function cusumFn(args) { return alter(args, function (eachSeries, base) { - var pairs = eachSeries.data; - var total = base || 0; + let pairs = eachSeries.data; + let total = base || 0; eachSeries.data = _.map(pairs, function (point, i) { total += point[1]; return [point[0], total]; diff --git a/src/core_plugins/timelion/server/series_functions/derivative.js b/src/core_plugins/timelion/server/series_functions/derivative.js index 4ec994e6dd470..0417112966f7d 100644 --- a/src/core_plugins/timelion/server/series_functions/derivative.js +++ b/src/core_plugins/timelion/server/series_functions/derivative.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('derivative', { args: [ { @@ -11,7 +11,7 @@ module.exports = new Chainable('derivative', { help: 'Plot the change in values over time.', fn: function derivativeFn(args) { return alter(args, function (eachSeries) { - var pairs = eachSeries.data; + let pairs = eachSeries.data; eachSeries.data = _.map(pairs, function (point, i) { if (i === 0 || pairs[i - 1][1] == null || point[1] == null) { return [point[0], null]; } return [point[0], point[1] - pairs[i - 1][1]]; diff --git a/src/core_plugins/timelion/server/series_functions/divide.js b/src/core_plugins/timelion/server/series_functions/divide.js index 00264a98ab772..ef6c78fb751b8 100644 --- a/src/core_plugins/timelion/server/series_functions/divide.js +++ b/src/core_plugins/timelion/server/series_functions/divide.js @@ -1,6 +1,6 @@ -var reduce = require('../lib/reduce.js'); +let reduce = require('../lib/reduce.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('divide', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/es/index.js b/src/core_plugins/timelion/server/series_functions/es/index.js index 16b1c13fcc1bb..7d63f564733b4 100644 --- a/src/core_plugins/timelion/server/series_functions/es/index.js +++ b/src/core_plugins/timelion/server/series_functions/es/index.js @@ -1,8 +1,8 @@ -var _ = require('lodash'); -var moment = require('moment'); -var toMS = require('../../lib/to_milliseconds.js'); -var Datasource = require('../../lib/classes/datasource'); -var buildRequest = require('./lib/build_request'); +let _ = require('lodash'); +let moment = require('moment'); +let toMS = require('../../lib/to_milliseconds.js'); +let Datasource = require('../../lib/classes/datasource'); +let buildRequest = require('./lib/build_request'); import toSeriesList from './lib/agg_response_to_series_list'; module.exports = new Datasource('es', { @@ -51,7 +51,7 @@ module.exports = new Datasource('es', { aliases: ['elasticsearch'], fn: function esFn(args, tlConfig) { - var config = _.defaults(_.clone(args.byName), { + let config = _.defaults(_.clone(args.byName), { q: '*', metric: ['count'], index: tlConfig.settings['timelion:es.default_index'], @@ -61,9 +61,9 @@ module.exports = new Datasource('es', { fit: 'nearest' }); - var callWithRequest = tlConfig.server.plugins.elasticsearch.callWithRequest; + let callWithRequest = tlConfig.server.plugins.elasticsearch.callWithRequest; - var body = buildRequest(config, tlConfig); + let body = buildRequest(config, tlConfig); return callWithRequest(tlConfig.request, 'search', body).then(function (resp) { if (!resp._shards.total) throw new Error('Elasticsearch index not found: ' + config.index); return { diff --git a/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js b/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js index 460f4eabe3000..47b920fb54a54 100644 --- a/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js +++ b/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js @@ -1,8 +1,8 @@ -var _ = require('lodash'); +let _ = require('lodash'); export function timeBucketsToPairs(buckets) { - var timestamps = _.pluck(buckets, 'key'); - var series = {}; + let timestamps = _.pluck(buckets, 'key'); + let series = {}; _.each(buckets, function (bucket) { _.forOwn(bucket, function (val, key) { if (_.isPlainObject(val)) { @@ -28,7 +28,7 @@ export function flattenBucket(bucket, path, result) { flattenBucket(bucket, path.concat([key + ':' + bucket.key]), result); }); } else if (_.get(val, 'meta.type') === 'time_buckets') { - var metrics = timeBucketsToPairs(val.buckets); + let metrics = timeBucketsToPairs(val.buckets); _.each(metrics, function (pairs, metricName) { result[path.concat([metricName]).join(' > ')] = pairs; }); diff --git a/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js b/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js index 7919f3ab7de1d..21d0091028d24 100644 --- a/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js +++ b/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); -var createDateAgg = require('./create_date_agg'); +let _ = require('lodash'); +let createDateAgg = require('./create_date_agg'); module.exports = function buildRequest(config, tlConfig) { - var bool = {must: [], must_not: []}; + let bool = {must: [], must_not: []}; - var timeFilter = {range:{}}; + let timeFilter = {range:{}}; timeFilter.range[config.timefield] = {gte: tlConfig.time.from, lte: tlConfig.time.to, format: 'epoch_millis'}; bool.must.push(timeFilter); @@ -14,7 +14,7 @@ module.exports = function buildRequest(config, tlConfig) { bool.filter = _.get(tlConfig, 'request.payload.extended.es.filter') || {}; } - var aggs = { + let aggs = { 'q': { meta: {type: 'split'}, filters: { @@ -26,7 +26,7 @@ module.exports = function buildRequest(config, tlConfig) { } }; - var aggCursor = aggs.q.aggs; + let aggCursor = aggs.q.aggs; _.each(config.split, function (clause, i) { clause = clause.split(':'); diff --git a/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js b/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js index e10d528195b85..b448baa45ec1e 100644 --- a/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js +++ b/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function createDateAgg(config, tlConfig) { - var dateAgg = { + let dateAgg = { time_buckets: { meta: {type: 'time_buckets'}, date_histogram: { @@ -30,7 +30,7 @@ module.exports = function createDateAgg(config, tlConfig) { } }; } else if (metric[0] && metric[1]) { - var metricName = metric[0] + '(' + metric[1] + ')'; + let metricName = metric[0] + '(' + metric[1] + ')'; dateAgg.time_buckets.aggs[metricName] = {}; dateAgg.time_buckets.aggs[metricName][metric[0]] = {field: metric[1]}; } else { diff --git a/src/core_plugins/timelion/server/series_functions/first.js b/src/core_plugins/timelion/server/series_functions/first.js index 8050da904dac3..5d82c1da22a82 100644 --- a/src/core_plugins/timelion/server/series_functions/first.js +++ b/src/core_plugins/timelion/server/series_functions/first.js @@ -1,5 +1,5 @@ -var alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('first', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/fit.js b/src/core_plugins/timelion/server/series_functions/fit.js index c5722791f5a8d..f2b3afcb84cb1 100644 --- a/src/core_plugins/timelion/server/series_functions/fit.js +++ b/src/core_plugins/timelion/server/series_functions/fit.js @@ -1,9 +1,9 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); -var loadFunctions = require('../lib/load_functions.js'); -var fitFunctions = loadFunctions('fit_functions'); +let loadFunctions = require('../lib/load_functions.js'); +let fitFunctions = loadFunctions('fit_functions'); module.exports = new Chainable('fit', { args: [ @@ -21,7 +21,7 @@ module.exports = new Chainable('fit', { fn: function absFn(args) { return alter(args, function (eachSeries, mode) { - var noNulls = _.filter(eachSeries.data, 1); + let noNulls = _.filter(eachSeries.data, 1); eachSeries.data = fitFunctions[mode](noNulls, eachSeries.data); return eachSeries; diff --git a/src/core_plugins/timelion/server/series_functions/graphite.js b/src/core_plugins/timelion/server/series_functions/graphite.js index 8315335801dd1..bb46ab20a57c2 100644 --- a/src/core_plugins/timelion/server/series_functions/graphite.js +++ b/src/core_plugins/timelion/server/series_functions/graphite.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); -var fetch = require('node-fetch'); -var moment = require('moment'); -var Datasource = require('../lib/classes/datasource'); +let _ = require('lodash'); +let fetch = require('node-fetch'); +let moment = require('moment'); +let Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('graphite', { @@ -15,14 +15,14 @@ module.exports = new Datasource ('graphite', { help: `[experimental] Pull data from graphite. Configure your graphite server in Kibana's Advanced Settings`, fn: function graphite(args, tlConfig) { - var config = args.byName; + let config = args.byName; - var time = { + let time = { min: moment(tlConfig.time.from).format('HH:mm[_]YYYYMMDD'), max: moment(tlConfig.time.to).format('HH:mm[_]YYYYMMDD') }; - var URL = tlConfig.settings['timelion:graphite.url'] + '/render/' + + let URL = tlConfig.settings['timelion:graphite.url'] + '/render/' + '?format=json' + '&from=' + time.min + '&until=' + time.max + @@ -31,8 +31,8 @@ module.exports = new Datasource ('graphite', { return fetch(URL).then(function (resp) { return resp.json(); }).then(function (resp) { - var list = _.map(resp, function (series) { - var data = _.map(series.datapoints, function (point) { + let list = _.map(resp, function (series) { + let data = _.map(series.datapoints, function (point) { return [point[1] * 1000, point[0]]; }); return { diff --git a/src/core_plugins/timelion/server/series_functions/hide.js b/src/core_plugins/timelion/server/series_functions/hide.js index 9e556b296a561..a49e550d6f499 100644 --- a/src/core_plugins/timelion/server/series_functions/hide.js +++ b/src/core_plugins/timelion/server/series_functions/hide.js @@ -1,5 +1,5 @@ -var alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('hide', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/holt/index.js b/src/core_plugins/timelion/server/series_functions/holt/index.js index d10543702e3d6..09405a4ea3a9a 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/index.js +++ b/src/core_plugins/timelion/server/series_functions/holt/index.js @@ -1,9 +1,9 @@ -var _ = require('lodash'); -var Chainable = require('../../lib/classes/chainable'); -var ses = require('./lib/ses'); -var des = require('./lib/des'); -var tes = require('./lib/tes'); -var toMilliseconds = require('../../lib/to_milliseconds'); +let _ = require('lodash'); +let Chainable = require('../../lib/classes/chainable'); +let ses = require('./lib/ses'); +let des = require('./lib/des'); +let tes = require('./lib/tes'); +let toMilliseconds = require('../../lib/to_milliseconds'); module.exports = new Chainable('holt', { args: [ @@ -71,8 +71,8 @@ module.exports = new Chainable('holt', { // points exponentially degrade relative to the alpha, eg: // 0.8^1, 0.8^2, 0.8^3, etc - var times = _.map(series.data, 0); - var points = _.map(series.data, 1); + let times = _.map(series.data, 0); + let points = _.map(series.data, 1); if (alpha != null && beta == null && gamma == null) { points = ses(points, alpha); diff --git a/src/core_plugins/timelion/server/series_functions/holt/lib/des.js b/src/core_plugins/timelion/server/series_functions/holt/lib/des.js index df01e461e2c18..28ee345584a93 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/lib/des.js +++ b/src/core_plugins/timelion/server/series_functions/holt/lib/des.js @@ -1,19 +1,19 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = function des(points, alpha, beta) { - var level; - var prevLevel; - var trend; - var prevTrend; - var value; - var origin; - var unknownCount = 0; + let level; + let prevLevel; + let trend; + let prevTrend; + let value; + let origin; + let unknownCount = 0; if (points.length < 2) { throw new Error ('You need at least 2 points to use double exponential smoothing'); } - var smoothedPoints = _.map(points, (point, i) => { + let smoothedPoints = _.map(points, (point, i) => { if (i === 0) { return point; } diff --git a/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js b/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js index 7a85565a00f08..e5e9dd46691c5 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js +++ b/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js @@ -8,7 +8,7 @@ module.exports = function ses(points, alpha) { let origin; let level; - var smoothedPoints = _.reduce(points, (result, point, i) => { + let smoothedPoints = _.reduce(points, (result, point, i) => { if (i === 0) { origin = point; level = point; diff --git a/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js b/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js index 5ba68d6d97183..b634ff229103f 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js +++ b/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js @@ -8,13 +8,13 @@ Hourly data might have: - Annual seasonality (frequency=24×365.25=8766) */ -var _ = require('lodash'); +let _ = require('lodash'); // Uh, I don't think this will work when you have nulls in the initial seasonal components function initSeasonalComponents(samplePoints, seasonLength) { - var sampledSeasonCount = samplePoints.length / seasonLength; - var currentSeason = []; - var seasonalAverages = _.reduce(samplePoints, (result, point, i) => { + let sampledSeasonCount = samplePoints.length / seasonLength; + let currentSeason = []; + let seasonalAverages = _.reduce(samplePoints, (result, point, i) => { currentSeason.push(point); // If this is the end of the season, add it to the result; if (i % seasonLength === seasonLength - 1) { @@ -25,8 +25,8 @@ function initSeasonalComponents(samplePoints, seasonLength) { return result; }, []); - var seasonals = _.times(seasonLength, (i) => { - var sumOfValsOverAvg = 0; + let seasonals = _.times(seasonLength, (i) => { + let sumOfValsOverAvg = 0; _.times(sampledSeasonCount, (j) => { sumOfValsOverAvg += samplePoints[seasonLength * j + i] - seasonalAverages[j]; }); @@ -40,7 +40,7 @@ function initSeasonalComponents(samplePoints, seasonLength) { // This is different from the DES method of establishing trend because it looks for // the difference in points between seasons function initTrend(samplePoints, seasonLength) { - var sum = 0; + let sum = 0; _.times(seasonLength, (i) => { sum += (samplePoints[i + seasonLength] - samplePoints[i]) / seasonLength; }); @@ -49,15 +49,15 @@ function initTrend(samplePoints, seasonLength) { module.exports = function tes(points, alpha, beta, gamma, seasonLength, seasonsToSample) { - var samplePoints = points.slice(0, seasonLength * seasonsToSample); - var seasonals = initSeasonalComponents(samplePoints, seasonLength); - var level; - var prevLevel; - var trend; - var prevTrend; - var unknownCount = 0; + let samplePoints = points.slice(0, seasonLength * seasonsToSample); + let seasonals = initSeasonalComponents(samplePoints, seasonLength); + let level; + let prevLevel; + let trend; + let prevTrend; + let unknownCount = 0; - var result = _.map(points, (point, i) => { + let result = _.map(points, (point, i) => { const seasonalPosition = i % seasonLength; // For the first samplePoints.length we use the actual points // After that we switch to the forecast diff --git a/src/core_plugins/timelion/server/series_functions/label.js b/src/core_plugins/timelion/server/series_functions/label.js index cfaaf513a1815..fbc5d3c237760 100644 --- a/src/core_plugins/timelion/server/series_functions/label.js +++ b/src/core_plugins/timelion/server/series_functions/label.js @@ -1,7 +1,7 @@ -var alter = require('../lib/alter.js'); -var util = require('util'); +let alter = require('../lib/alter.js'); +let util = require('util'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('label', { args: [ { @@ -21,7 +21,7 @@ module.exports = new Chainable('label', { ], help: 'Change the label of the series. Use %s reference the existing label', fn: function labelFn(args) { - var config = args.byName; + let config = args.byName; return alter(args, function (eachSeries) { if (config.regex) { eachSeries.label = eachSeries.label.replace(new RegExp(config.regex), config.label); diff --git a/src/core_plugins/timelion/server/series_functions/legend.js b/src/core_plugins/timelion/server/series_functions/legend.js index c81eabb4dddb5..faa6f81884698 100644 --- a/src/core_plugins/timelion/server/series_functions/legend.js +++ b/src/core_plugins/timelion/server/series_functions/legend.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); +let alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('legend', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/lines.js b/src/core_plugins/timelion/server/series_functions/lines.js index 9b9a9fd5a90be..720e4bfdaf066 100644 --- a/src/core_plugins/timelion/server/series_functions/lines.js +++ b/src/core_plugins/timelion/server/series_functions/lines.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); +let alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('lines', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/log.js b/src/core_plugins/timelion/server/series_functions/log.js index 9844394b31f9b..88a90eefba9fc 100644 --- a/src/core_plugins/timelion/server/series_functions/log.js +++ b/src/core_plugins/timelion/server/series_functions/log.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('log', { args: [ { @@ -16,9 +16,9 @@ module.exports = new Chainable('log', { ], help: 'Return the logarithm value of each value in the series list (default base: 10)', fn: function logFn(args) { - var config = args.byName; + let config = args.byName; return alter(args, function (eachSeries) { - var data = _.map(eachSeries.data, function (point) { + let data = _.map(eachSeries.data, function (point) { return [point[0], Math.log(point[1]) / Math.log(config.base || 10)]; }); eachSeries.data = data; diff --git a/src/core_plugins/timelion/server/series_functions/max.js b/src/core_plugins/timelion/server/series_functions/max.js index 8f5613d84c8b8..2012f9b74daad 100644 --- a/src/core_plugins/timelion/server/series_functions/max.js +++ b/src/core_plugins/timelion/server/series_functions/max.js @@ -1,6 +1,6 @@ -var reduce = require('../lib/reduce.js'); +let reduce = require('../lib/reduce.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('max', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/min.js b/src/core_plugins/timelion/server/series_functions/min.js index 7a2a14ce8b61d..f5f4cce4dc14d 100644 --- a/src/core_plugins/timelion/server/series_functions/min.js +++ b/src/core_plugins/timelion/server/series_functions/min.js @@ -1,6 +1,6 @@ -var reduce = require('../lib/reduce.js'); +let reduce = require('../lib/reduce.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('min', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/movingaverage.js b/src/core_plugins/timelion/server/series_functions/movingaverage.js index 6070a4c81aed9..129ffb5f58515 100644 --- a/src/core_plugins/timelion/server/series_functions/movingaverage.js +++ b/src/core_plugins/timelion/server/series_functions/movingaverage.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('movingaverage', { args: [ { @@ -24,15 +24,15 @@ module.exports = new Chainable('movingaverage', { return alter(args, function (eachSeries, _window, _position) { _position = _position || 'center'; - var validPositions = ['left', 'right', 'center']; + let validPositions = ['left', 'right', 'center']; if (!_.contains(validPositions, _position)) throw new Error('Valid positions are: ' + validPositions.join(', ')); - var pairs = eachSeries.data; - var pairsLen = pairs.length; + let pairs = eachSeries.data; + let pairsLen = pairs.length; eachSeries.label = eachSeries.label + ' mvavg=' + _window; function toPoint(point, pairSlice) { - var average = _.chain(pairSlice) + let average = _.chain(pairSlice) .map(1).reduce(function (memo, num) { return (memo + num); }).value() / _window; @@ -41,8 +41,8 @@ module.exports = new Chainable('movingaverage', { } if (_position === 'center') { - var windowLeft = Math.floor(_window / 2); - var windowRight = _window - windowLeft; + let windowLeft = Math.floor(_window / 2); + let windowRight = _window - windowLeft; eachSeries.data = _.map(pairs, function (point, i) { if (i < windowLeft || i >= pairsLen - windowRight) return [point[0], null]; return toPoint(point, pairs.slice(i - windowLeft, i + windowRight)); diff --git a/src/core_plugins/timelion/server/series_functions/movingstd.js b/src/core_plugins/timelion/server/series_functions/movingstd.js index 06c87f6bf2a05..9dc7270be8fbc 100644 --- a/src/core_plugins/timelion/server/series_functions/movingstd.js +++ b/src/core_plugins/timelion/server/series_functions/movingstd.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('movingstd', { args: [ { @@ -19,19 +19,19 @@ module.exports = new Chainable('movingstd', { fn: function movingstdFn(args) { return alter(args, function (eachSeries, _window) { - var pairs = eachSeries.data; + let pairs = eachSeries.data; eachSeries.data = _.map(pairs, function (point, i) { if (i < _window) { return [point[0], null]; } - var average = _.chain(pairs.slice(i - _window, i)) + let average = _.chain(pairs.slice(i - _window, i)) .map(function (point) { return point[1]; }).reduce(function (memo, num) { return (memo + num); }).value() / _window; - var variance = _.chain(pairs.slice(i - _window, i)) + let variance = _.chain(pairs.slice(i - _window, i)) .map(function (point) { return point[1]; }).reduce(function (memo, num) { diff --git a/src/core_plugins/timelion/server/series_functions/multiply.js b/src/core_plugins/timelion/server/series_functions/multiply.js index 7f7a22f2c16e8..f88b7dcb5eafa 100644 --- a/src/core_plugins/timelion/server/series_functions/multiply.js +++ b/src/core_plugins/timelion/server/series_functions/multiply.js @@ -1,6 +1,6 @@ -var reduce = require('../lib/reduce.js'); +let reduce = require('../lib/reduce.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('multiply', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/points.js b/src/core_plugins/timelion/server/series_functions/points.js index e5a25d00e59ed..9bfd4f1c21537 100644 --- a/src/core_plugins/timelion/server/series_functions/points.js +++ b/src/core_plugins/timelion/server/series_functions/points.js @@ -1,7 +1,7 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('points', { args: [ { @@ -58,7 +58,7 @@ module.exports = new Chainable('points', { } symbol = symbol || 'circle'; - var validSymbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; + let validSymbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; if (!_.contains(['triangle', 'cross', 'square', 'diamond', 'circle'], symbol)) { throw new Error('Valid symbols are: ' + validSymbols.join(', ')); } diff --git a/src/core_plugins/timelion/server/series_functions/precision.js b/src/core_plugins/timelion/server/series_functions/precision.js index 20f78e8b295e4..64a601298d32c 100644 --- a/src/core_plugins/timelion/server/series_functions/precision.js +++ b/src/core_plugins/timelion/server/series_functions/precision.js @@ -1,8 +1,8 @@ -var reduce = require('../lib/reduce.js'); -var alter = require('../lib/alter.js'); +let reduce = require('../lib/reduce.js'); +let alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('precision', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/props.js b/src/core_plugins/timelion/server/series_functions/props.js index 15dfba27c9092..52edaad703e6b 100644 --- a/src/core_plugins/timelion/server/series_functions/props.js +++ b/src/core_plugins/timelion/server/series_functions/props.js @@ -1,16 +1,16 @@ -var alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); -var _ = require('lodash'); +let alter = require('../lib/alter.js'); +let Chainable = require('../lib/classes/chainable'); +let _ = require('lodash'); function unflatten(data) { if (Object(data) !== data || _.isArray(data)) return data; - var regex = new RegExp(/\.?([^.\[\]]+)|\[(\d+)\]/g); - var result = {}; + let regex = new RegExp(/\.?([^.\[\]]+)|\[(\d+)\]/g); + let result = {}; _.each(data, function (val, p) { - var cur = result; - var prop = ''; - var m; + let cur = result; + let prop = ''; + let m; while (m = regex.exec(p)) { cur = cur[prop] || (cur[prop] = (m[2] ? [] : {})); prop = m[2] || m[1]; @@ -43,7 +43,7 @@ module.exports = new Chainable('props', { // They will be passed as args._extended:{} help: 'Use at your own risk, sets arbitrary properties on the series. For example .props(label=bears!)', fn: function firstFn(args) { - var properties = unflatten(_.omit(args.byName, 'inputSeries', 'global')); + let properties = unflatten(_.omit(args.byName, 'inputSeries', 'global')); if (args.byName.global) { _.assign(args.byName.inputSeries, properties); diff --git a/src/core_plugins/timelion/server/series_functions/quandl.js b/src/core_plugins/timelion/server/series_functions/quandl.js index c438de17e2382..d209e1db0b87f 100644 --- a/src/core_plugins/timelion/server/series_functions/quandl.js +++ b/src/core_plugins/timelion/server/series_functions/quandl.js @@ -1,11 +1,11 @@ -var _ = require('lodash'); -var fetch = require('node-fetch'); -var moment = require('moment'); +let _ = require('lodash'); +let fetch = require('node-fetch'); +let moment = require('moment'); fetch.Promise = require('bluebird'); //var parseDateMath = require('../utils/date_math.js'); -var Datasource = require('../lib/classes/datasource'); +let Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('quandl', { @@ -27,14 +27,14 @@ module.exports = new Datasource ('quandl', { Pull data from quandl.com using the quandl code. Set "timelion:quandl.key" to your free API key in Kibana's Advanced Settings. The API has a really low rate limit without a key.`, fn: function quandlFn(args, tlConfig) { - var intervalMap = { + let intervalMap = { '1d': 'daily', '1w': 'weekly', '1M': 'monthly', '1y': 'annual', }; - var config = _.defaults(args.byName, { + let config = _.defaults(args.byName, { code: 'WIKI/AAPL', position: 1, interval: intervalMap[tlConfig.time.interval], @@ -46,7 +46,7 @@ module.exports = new Datasource ('quandl', { '. quandl() supports: ' + _.keys(intervalMap).join(', ')); } - var time = { + let time = { min: moment.utc(tlConfig.time.from).format('YYYY-MM-DD'), max: moment.utc(tlConfig.time.to).format('YYYY-MM-DD') }; @@ -58,7 +58,7 @@ module.exports = new Datasource ('quandl', { // 4. close // 5. volume - var URL = 'https://www.quandl.com/api/v1/datasets/' + config.code + '.json' + + let URL = 'https://www.quandl.com/api/v1/datasets/' + config.code + '.json' + '?sort_order=asc' + '&trim_start=' + time.min + '&trim_end=' + time.max + @@ -66,7 +66,7 @@ module.exports = new Datasource ('quandl', { '&auth_token=' + config.apikey; return fetch(URL).then(function (resp) { return resp.json(); }).then(function (resp) { - var data = _.map(resp.data, function (bucket) { + let data = _.map(resp.data, function (bucket) { return [moment(bucket[0]).valueOf(), bucket[config.position]]; }); diff --git a/src/core_plugins/timelion/server/series_functions/range.js b/src/core_plugins/timelion/server/series_functions/range.js index 8fc1c7a078c26..f0747f1966226 100644 --- a/src/core_plugins/timelion/server/series_functions/range.js +++ b/src/core_plugins/timelion/server/series_functions/range.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('range', { args: [ { @@ -21,13 +21,13 @@ module.exports = new Chainable('range', { help: 'Changes the max and min of a series while keeping the same shape', fn: function range(args) { return alter(args, function (eachSeries) { - var values = _.map(eachSeries.data, 1); - var min = _.min(values); - var max = _.max(values); + let values = _.map(eachSeries.data, 1); + let min = _.min(values); + let max = _.max(values); // newvalue= (max'-min')/(max-min)*(value-min)+min'. - var data = _.map(eachSeries.data, function (point) { - var val = (args.byName.max - args.byName.min) / + let data = _.map(eachSeries.data, function (point) { + let val = (args.byName.max - args.byName.min) / (max - min) * (point[1] - min) + args.byName.min; return [point[0], val]; }); diff --git a/src/core_plugins/timelion/server/series_functions/scale_interval.js b/src/core_plugins/timelion/server/series_functions/scale_interval.js index f6434123af39a..77b2d2deacc6b 100644 --- a/src/core_plugins/timelion/server/series_functions/scale_interval.js +++ b/src/core_plugins/timelion/server/series_functions/scale_interval.js @@ -1,8 +1,8 @@ -var alter = require('../lib/alter.js'); -var toMS = require('../lib/to_milliseconds.js'); +let alter = require('../lib/alter.js'); +let toMS = require('../lib/to_milliseconds.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('scale_interval', { args: [ { @@ -17,11 +17,11 @@ module.exports = new Chainable('scale_interval', { ], help: 'Changes scales a value (usually a sum or a count) to a new interval. For example, as a per-second rate', fn: function scaleIntervalFn(args, tlConfig) { - var currentInterval = toMS(tlConfig.time.interval); - var scaleInterval = toMS(args.byName.interval); + let currentInterval = toMS(tlConfig.time.interval); + let scaleInterval = toMS(args.byName.interval); return alter(args, function (eachSeries) { - var data = _.map(eachSeries.data, function (point) { + let data = _.map(eachSeries.data, function (point) { return [point[0], (point[1] / currentInterval) * scaleInterval]; }); eachSeries.data = data; diff --git a/src/core_plugins/timelion/server/series_functions/static.js b/src/core_plugins/timelion/server/series_functions/static.js index f4dfa4234086c..32a69a5766a4f 100644 --- a/src/core_plugins/timelion/server/series_functions/static.js +++ b/src/core_plugins/timelion/server/series_functions/static.js @@ -1,8 +1,8 @@ -var _ = require('lodash'); -var fetch = require('node-fetch'); -var moment = require('moment'); -var Datasource = require('../lib/classes/datasource'); -var Promise = require('bluebird'); +let _ = require('lodash'); +let fetch = require('node-fetch'); +let moment = require('moment'); +let Datasource = require('../lib/classes/datasource'); +let Promise = require('bluebird'); module.exports = new Datasource ('static', { @@ -23,13 +23,13 @@ module.exports = new Datasource ('static', { help: 'Draws a single value across the chart', fn: function staticFn(args, tlConfig) { - var data; - var target = tlConfig.getTargetSeries(); + let data; + let target = tlConfig.getTargetSeries(); if (typeof args.byName.value === 'string') { - var points = args.byName.value.split(':'); - var begin = _.first(target)[0]; - var end = _.last(target)[0]; - var step = (end - begin) / (points.length - 1); + let points = args.byName.value.split(':'); + let begin = _.first(target)[0]; + let end = _.last(target)[0]; + let step = (end - begin) / (points.length - 1); data = _.map(points, function (point, i) { return [begin + (i * step), parseFloat(point)]; }); diff --git a/src/core_plugins/timelion/server/series_functions/subtract.js b/src/core_plugins/timelion/server/series_functions/subtract.js index 499a51123c3a6..4848f502c59cc 100644 --- a/src/core_plugins/timelion/server/series_functions/subtract.js +++ b/src/core_plugins/timelion/server/series_functions/subtract.js @@ -1,7 +1,7 @@ -var reduce = require('../lib/reduce.js'); +let reduce = require('../lib/reduce.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('subtract', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/sum.js b/src/core_plugins/timelion/server/series_functions/sum.js index d85f164b19fe2..0b0f258083c04 100644 --- a/src/core_plugins/timelion/server/series_functions/sum.js +++ b/src/core_plugins/timelion/server/series_functions/sum.js @@ -1,6 +1,6 @@ -var reduce = require('../lib/reduce.js'); +let reduce = require('../lib/reduce.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('sum', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/title.js b/src/core_plugins/timelion/server/series_functions/title.js index 84dc88fba8290..c53c4caa7d4e6 100644 --- a/src/core_plugins/timelion/server/series_functions/title.js +++ b/src/core_plugins/timelion/server/series_functions/title.js @@ -1,5 +1,5 @@ -var alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let alter = require('../lib/alter.js'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('title', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/trend/index.js b/src/core_plugins/timelion/server/series_functions/trend/index.js index 59de64f43b34b..fe8848a6ac331 100644 --- a/src/core_plugins/timelion/server/series_functions/trend/index.js +++ b/src/core_plugins/timelion/server/series_functions/trend/index.js @@ -1,8 +1,8 @@ -var _ = require('lodash'); -var Chainable = require('../../lib/classes/chainable'); +let _ = require('lodash'); +let Chainable = require('../../lib/classes/chainable'); import * as regress from './lib/regress'; -var validRegressions = { +let validRegressions = { linear: 'linear', log: 'logarithmic', }; diff --git a/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js b/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js index 7bc645c360f99..5bb4119e5fc21 100644 --- a/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js +++ b/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js @@ -4,7 +4,7 @@ * Licensed under the MIT license. */ -var _ = require('lodash'); +let _ = require('lodash'); function sum(data, fn) { return _.reduce(data, function (sum, d) { @@ -25,34 +25,34 @@ function mapTuples(data, fn) { } export function linear(data) { - var xSum = sum(data, (d) => {return d[0]; }); - var ySum = sum(data, (d) => {return d[1]; }); - var xSqSum = sum(data, (d) => {return d[0] * d[0]; }); - var xySum = sum(data, (d) => {return d[0] * d[1]; }); - var observations = count(data); + let xSum = sum(data, (d) => {return d[0]; }); + let ySum = sum(data, (d) => {return d[1]; }); + let xSqSum = sum(data, (d) => {return d[0] * d[0]; }); + let xySum = sum(data, (d) => {return d[0] * d[1]; }); + let observations = count(data); - var gradient = + let gradient = ((observations * xySum) - (xSum * ySum)) / ((observations * xSqSum) - (xSum * xSum)); - var intercept = + let intercept = (ySum / observations) - (gradient * xSum) / observations; return mapTuples(data, (d) => { return d[0] * gradient + intercept; }); } export function log(data) { - var logXSum = sum(data, (d) => {return Math.log(d[0]); }); - var yLogXSum = sum(data, (d) => {return d[1] * Math.log(d[0]); }); - var ySum = sum(data, (d) => {return d[1]; }); - var logXsqSum = sum(data, (d) => {return Math.pow(Math.log(d[0]), 2); }); - var observations = count(data); + let logXSum = sum(data, (d) => {return Math.log(d[0]); }); + let yLogXSum = sum(data, (d) => {return d[1] * Math.log(d[0]); }); + let ySum = sum(data, (d) => {return d[1]; }); + let logXsqSum = sum(data, (d) => {return Math.pow(Math.log(d[0]), 2); }); + let observations = count(data); - var b = + let b = ((observations * yLogXSum) - (ySum * logXSum)) / ((observations * logXsqSum) - (logXSum * logXSum)); - var a = + let a = (ySum - b * logXSum) / observations; diff --git a/src/core_plugins/timelion/server/series_functions/trim.js b/src/core_plugins/timelion/server/series_functions/trim.js index 8759b0a70c6ab..64bae6d2b086a 100644 --- a/src/core_plugins/timelion/server/series_functions/trim.js +++ b/src/core_plugins/timelion/server/series_functions/trim.js @@ -1,7 +1,7 @@ -var alter = require('../lib/alter.js'); -var _ = require('lodash'); -var Chainable = require('../lib/classes/chainable'); -var argType = require('../handlers/lib/arg_type.js'); +let alter = require('../lib/alter.js'); +let _ = require('lodash'); +let Chainable = require('../lib/classes/chainable'); +let argType = require('../handlers/lib/arg_type.js'); module.exports = new Chainable('trim', { args: [ @@ -22,7 +22,7 @@ module.exports = new Chainable('trim', { ], help: 'Set N buckets at the start or end of a series to null to fit the "partial bucket issue"', fn: function conditionFn(args) { - var config = args.byName; + let config = args.byName; if (config.start == null) config.start = 1; if (config.end == null) config.end = 1; diff --git a/src/core_plugins/timelion/server/series_functions/worldbank.js b/src/core_plugins/timelion/server/series_functions/worldbank.js index bbab3aae1baf2..3301b70e68e03 100644 --- a/src/core_plugins/timelion/server/series_functions/worldbank.js +++ b/src/core_plugins/timelion/server/series_functions/worldbank.js @@ -1,7 +1,7 @@ -var _ = require('lodash'); -var fetch = require('node-fetch'); -var moment = require('moment'); -var Datasource = require('../lib/classes/datasource'); +let _ = require('lodash'); +let fetch = require('node-fetch'); +let moment = require('moment'); +let Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('worldbank', { args: [ @@ -22,34 +22,34 @@ module.exports = new Datasource ('worldbank', { fn: function worldbank(args, tlConfig) { // http://api.worldbank.org/en/countries/ind;chn/indicators/DPANUSSPF?date=2000:2006&MRV=5 - var config = _.defaults(args.byName, { + let config = _.defaults(args.byName, { code: 'countries/wld/indicators/SP.POP.TOTL' }); - var time = { + let time = { min: moment(tlConfig.time.from).format('YYYY'), max: moment(tlConfig.time.to).format('YYYY') }; - var URL = 'http://api.worldbank.org/' + config.code + + let URL = 'http://api.worldbank.org/' + config.code + '?date=' + time.min + ':' + time.max + '&format=json' + '&per_page=1000'; return fetch(URL).then(function (resp) { return resp.json(); }).then(function (resp) { - var hasData = false; + let hasData = false; - var respSeries = resp[1]; + let respSeries = resp[1]; - var deduped = {}; - var description; + let deduped = {}; + let description; _.each (respSeries, function (bucket) { if (bucket.value != null) hasData = true; description = bucket.country.value + ' ' + bucket.indicator.value; deduped[bucket.date] = bucket.value; }); - var data = _.compact(_.map(deduped, function (val, date) { + let data = _.compact(_.map(deduped, function (val, date) { // Discard nulls if (val == null) return; return [moment(date, 'YYYY').valueOf(), Number(val)]; diff --git a/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js b/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js index 7f87cf354a99c..8e5ffb4e30005 100644 --- a/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js +++ b/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js @@ -1,9 +1,9 @@ -var _ = require('lodash'); -var fetch = require('node-fetch'); -var moment = require('moment'); -var worldbank = require('./worldbank.js'); -var Promise = require('bluebird'); -var Datasource = require('../lib/classes/datasource'); +let _ = require('lodash'); +let fetch = require('node-fetch'); +let moment = require('moment'); +let worldbank = require('./worldbank.js'); +let Promise = require('bluebird'); +let Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('worldbank_indicators', { @@ -27,15 +27,15 @@ module.exports = new Datasource ('worldbank_indicators', { mostly yearly data, and often has no data for the current year. Try offset=-1y if you get no data for recent time ranges.`, fn: function worldbankIndicators(args, tlConfig) { - var config = _.defaults(args.byName, { + let config = _.defaults(args.byName, { country: 'wld', indicator: 'SP.POP.TOTL' }); - var countries = config.country.split(':'); - var seriesLists = _.map(countries, function (country) { - var code = 'countries/' + country + '/indicators/' + config.indicator; - var wbArgs = [code]; + let countries = config.country.split(':'); + let seriesLists = _.map(countries, function (country) { + let code = 'countries/' + country + '/indicators/' + config.indicator; + let wbArgs = [code]; wbArgs.byName = {code: code}; return worldbank.timelionFn(wbArgs, tlConfig); }); diff --git a/src/core_plugins/timelion/server/series_functions/yaxis.js b/src/core_plugins/timelion/server/series_functions/yaxis.js index 30bece32c57bc..5f6c781fad0cf 100644 --- a/src/core_plugins/timelion/server/series_functions/yaxis.js +++ b/src/core_plugins/timelion/server/series_functions/yaxis.js @@ -1,6 +1,6 @@ -var alter = require('../lib/alter.js'); +let alter = require('../lib/alter.js'); -var Chainable = require('../lib/classes/chainable'); +let Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('yaxis', { args: [ { @@ -49,7 +49,7 @@ module.exports = new Chainable('yaxis', { eachSeries._global.yaxes = eachSeries._global.yaxes || []; eachSeries._global.yaxes[yaxis - 1] = eachSeries._global.yaxes[yaxis - 1] || {}; - var myAxis = eachSeries._global.yaxes[yaxis - 1]; + let myAxis = eachSeries._global.yaxes[yaxis - 1]; myAxis.position = position || (yaxis % 2 ? 'left' : 'right'); myAxis.min = min == null ? 0 : min; myAxis.max = max; diff --git a/src/ui/public/directives/__tests__/paginated_selectable_list.js b/src/ui/public/directives/__tests__/paginated_selectable_list.js index eb18304b478ff..a066d470b4497 100644 --- a/src/ui/public/directives/__tests__/paginated_selectable_list.js +++ b/src/ui/public/directives/__tests__/paginated_selectable_list.js @@ -21,9 +21,9 @@ let stringList = [ let lists = [objectList, stringList, []]; -var $scope; -var $element; -var $isolatedScope; +let $scope; +let $element; +let $isolatedScope; lists.forEach(function (list) { let isArrayOfObjects = list.every((item) => { diff --git a/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js b/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js index 36614f1e9b7e9..bdb9759052e0d 100644 --- a/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js +++ b/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js @@ -303,7 +303,7 @@ describe('KbnTopNavController', function () { expect(controller.menuItems).to.have.length(4); // check that the items were added - var matches = controller.menuItems.reduce((acc, item) => { + let matches = controller.menuItems.reduce((acc, item) => { if (item.key === 'green' || item.key === 'red') { acc[item.key] = item; } @@ -324,7 +324,7 @@ describe('KbnTopNavController', function () { expect(controller.menuItems).to.have.length(3); // check that the items were added - var match = controller.menuItems.filter((item) => { + let match = controller.menuItems.filter((item) => { return item.key === 'green'; }); expect(match[0]).to.have.property('run'); diff --git a/src/ui/public/paginated_table/__tests__/index.js b/src/ui/public/paginated_table/__tests__/index.js index 34eea5692ab8c..945118d794a70 100644 --- a/src/ui/public/paginated_table/__tests__/index.js +++ b/src/ui/public/paginated_table/__tests__/index.js @@ -165,7 +165,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - var tableRows = $el.find('tbody tr'); + let tableRows = $el.find('tbody tr'); expect(tableRows.eq(2).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(1).find('td').eq(1).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); @@ -175,7 +175,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1, 'desc'); $scope.$digest(); - var tableRows = $el.find('tbody tr'); + let tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('zzzz'); expect(tableRows.eq(1).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(2).find('td').eq(1).text()).to.be('bbbb'); diff --git a/src/ui/public/pattern_checker/pattern_checker.js b/src/ui/public/pattern_checker/pattern_checker.js index 5ac8834d8a8e8..134bfce760f61 100644 --- a/src/ui/public/pattern_checker/pattern_checker.js +++ b/src/ui/public/pattern_checker/pattern_checker.js @@ -17,7 +17,7 @@ module.directive('patternChecker', function () { controller: function (Notifier, $scope, $timeout, $http) { let validationTimeout; - var notify = new Notifier({ + let notify = new Notifier({ location: 'Add Data' }); diff --git a/src/ui/public/vislib/__tests__/lib/layout/splits/column_chart/splits.js b/src/ui/public/vislib/__tests__/lib/layout/splits/column_chart/splits.js index dac0111531d9b..a4d8a02039fd1 100644 --- a/src/ui/public/vislib/__tests__/lib/layout/splits/column_chart/splits.js +++ b/src/ui/public/vislib/__tests__/lib/layout/splits/column_chart/splits.js @@ -173,9 +173,9 @@ describe('Vislib Split Function Test Suite', function () { }); describe('chart title split function', function () { - var visEl; - var newEl; - var fixture; + let visEl; + let newEl; + let fixture; beforeEach(ngMock.inject(function () { visEl = el.append('div').attr('class', 'vis-wrapper'); diff --git a/tasks/build/babel_options.js b/tasks/build/babel_options.js index 586e3cedd0e3a..9c8db68e28310 100644 --- a/tasks/build/babel_options.js +++ b/tasks/build/babel_options.js @@ -1,9 +1,9 @@ module.exports = function (grunt) { - var srcFile = 'build/kibana/src/optimize/babel_options.js'; - var buildFile = 'build/kibana/src/optimize/babel_options.build.js'; - var rename = require('fs').renameSync; - var unlink = require('fs').unlinkSync; + let srcFile = 'build/kibana/src/optimize/babel_options.js'; + let buildFile = 'build/kibana/src/optimize/babel_options.build.js'; + let rename = require('fs').renameSync; + let unlink = require('fs').unlinkSync; grunt.registerTask('_build:babelOptions', function () { unlink(srcFile); diff --git a/tasks/build/install_npm_deps.js b/tasks/build/install_npm_deps.js index e7198706f5c58..efebb5e5ac34b 100644 --- a/tasks/build/install_npm_deps.js +++ b/tasks/build/install_npm_deps.js @@ -1,6 +1,6 @@ module.exports = function (grunt) { - var { exec } = require('child_process'); - var { resolve } = require('path'); + let { exec } = require('child_process'); + let { resolve } = require('path'); grunt.registerTask('_build:installNpmDeps', function () { grunt.file.mkdir('build/kibana/node_modules'); diff --git a/tasks/build/shasums.js b/tasks/build/shasums.js index cb0b405c2ad2c..f6bc6a6ba8100 100644 --- a/tasks/build/shasums.js +++ b/tasks/build/shasums.js @@ -1,12 +1,12 @@ -var { promisify } = require('bluebird'); -var readdir = promisify(require('fs').readdir); -var exec = promisify(require('child_process').exec); -var platform = require('os').platform(); -var cmd = /^win/.test(platform) ? 'sha1sum ' : 'shasum '; +let { promisify } = require('bluebird'); +let readdir = promisify(require('fs').readdir); +let exec = promisify(require('child_process').exec); +let platform = require('os').platform(); +let cmd = /^win/.test(platform) ? 'sha1sum ' : 'shasum '; module.exports = function (grunt) { grunt.registerTask('_build:shasums', function () { - var targetDir = grunt.config.get('target'); + let targetDir = grunt.config.get('target'); // for when shasums is run but archives and ospackages was not grunt.file.mkdir(targetDir); diff --git a/tasks/config/esvm.js b/tasks/config/esvm.js index 91ebfb7b40b0e..52600ae78c941 100644 --- a/tasks/config/esvm.js +++ b/tasks/config/esvm.js @@ -1,8 +1,8 @@ module.exports = function (grunt) { - var resolve = require('path').resolve; - var directory = resolve(__dirname, '../../esvm'); - var dataDir = resolve(directory, 'data_dir'); - var serverConfig = require('../../test/server_config'); + let resolve = require('path').resolve; + let directory = resolve(__dirname, '../../esvm'); + let dataDir = resolve(directory, 'data_dir'); + let serverConfig = require('../../test/server_config'); return { options: { diff --git a/tasks/config/intern.js b/tasks/config/intern.js index 75d9567b364c1..8fc678855251e 100644 --- a/tasks/config/intern.js +++ b/tasks/config/intern.js @@ -1,4 +1,4 @@ -var path = require('path'); +let path = require('path'); module.exports = function (grunt) { diff --git a/tasks/config/s3.js b/tasks/config/s3.js index 19a1491412e2c..c9c1ff0e1a68b 100644 --- a/tasks/config/s3.js +++ b/tasks/config/s3.js @@ -1,5 +1,5 @@ module.exports = function (grunt) { - var { config } = grunt; + let { config } = grunt; return { release: { diff --git a/tasks/release_packages.js b/tasks/release_packages.js index 23701a91589fa..87accb94fd524 100644 --- a/tasks/release_packages.js +++ b/tasks/release_packages.js @@ -59,7 +59,7 @@ export default (grunt) => { grunt.fail.fatal('Aborting publish'); } - var rl = readline.createInterface({ + let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); diff --git a/tasks/sterilize.js b/tasks/sterilize.js index 11b827e5bbe62..7e194d440e9df 100644 --- a/tasks/sterilize.js +++ b/tasks/sterilize.js @@ -26,7 +26,7 @@ export default function (grunt) { rl.on('close', this.async()); rl.question(`\n${danger} Do you really want to delete all of the above files?, [N/y] `, function (resp) { - var yes = resp.toLowerCase().trim()[0] === 'y'; + let yes = resp.toLowerCase().trim()[0] === 'y'; rl.close(); if (yes) { diff --git a/tasks/utils/install_or_update_repo.js b/tasks/utils/install_or_update_repo.js index 588d43b63fd8f..f803cf33d5801 100644 --- a/tasks/utils/install_or_update_repo.js +++ b/tasks/utils/install_or_update_repo.js @@ -1,12 +1,12 @@ -var Promise = require('bluebird'); -var spawn = require('./spawn'); -var grunt = require('grunt'); +let Promise = require('bluebird'); +let spawn = require('./spawn'); +let grunt = require('grunt'); module.exports = function (repo, dir) { // store the previous and new hash from the repo // to know if there was an update from fetch - var prevHash; - var newHash; + let prevHash; + let newHash; return Promise.resolve() .then(function () { diff --git a/tasks/utils/update_version.js b/tasks/utils/update_version.js index 5180069ae2b96..e38436ab08cf2 100644 --- a/tasks/utils/update_version.js +++ b/tasks/utils/update_version.js @@ -1,8 +1,8 @@ -var _ = require('lodash'); +let _ = require('lodash'); module.exports = updateVersion; -var versions = [ +let versions = [ 'major', 'minor', 'patch', @@ -44,7 +44,7 @@ var versions = [ function updateVersion(version, expr) { expr = String(expr).split('='); - var change = { + let change = { name: expr[0], val: expr[1] || null }; @@ -58,7 +58,7 @@ function updateVersion(version, expr) { } // parse the current version - var parts = _.chain(version.split('.')) + let parts = _.chain(version.split('.')) // ensure that their are three pieces, either x.x.x or x.x.x-y .tap(function (versionNumbers) { @@ -70,7 +70,7 @@ function updateVersion(version, expr) { // describe all of the version parts with a name, parse // the numbers, and extract tag from patch .transform(function (parts, v, i) { - var name = versions[i]; + let name = versions[i]; if (name !== 'patch') { parts[name] = _.parseInt(v); @@ -86,7 +86,7 @@ function updateVersion(version, expr) { // sanity check .tap(function (parts) { - var valid = true; + let valid = true; valid = valid && _.isNumber(parts.major); valid = valid && _.isNumber(parts.minor); valid = valid && _.isNumber(parts.patch); @@ -121,7 +121,7 @@ function updateVersion(version, expr) { } // properties that are zero-d by the previous update - var emptyUpdates = versions.slice(versions.indexOf(change.name) + 1); + let emptyUpdates = versions.slice(versions.indexOf(change.name) + 1); while (emptyUpdates.length) { parts[emptyUpdates.shift()] = ''; } diff --git a/test/fixtures/__tests__/scenario_manager.js b/test/fixtures/__tests__/scenario_manager.js index 144f6c1cfaa80..fd271a388d6f8 100644 --- a/test/fixtures/__tests__/scenario_manager.js +++ b/test/fixtures/__tests__/scenario_manager.js @@ -1,18 +1,18 @@ -var expect = require('expect.js'); -var sinon = require('sinon'); -var Promise = require('bluebird'); +let expect = require('expect.js'); +let sinon = require('sinon'); +let Promise = require('bluebird'); -var ScenarioManager = require('../scenario_manager'); +let ScenarioManager = require('../scenario_manager'); describe('scenario manager', function () { - var manager = new ScenarioManager('http://localhost:9200'); + let manager = new ScenarioManager('http://localhost:9200'); describe('loading and unloading', function () { this.timeout(60000); - var bulk; - var create; - var indicesDelete; + let bulk; + let create; + let indicesDelete; beforeEach(function () { bulk = sinon.stub(manager.client, 'bulk', Promise.resolve); create = sinon.stub(manager.client.indices, 'create', Promise.resolve); @@ -43,9 +43,9 @@ describe('scenario manager', function () { }); it('should be able to reload a scenario', function () { - var load = sinon.stub(manager, 'load', Promise.resolve); - var unload = sinon.stub(manager, 'unload', Promise.resolve); - var id = 'makelogs'; + let load = sinon.stub(manager, 'load', Promise.resolve); + let unload = sinon.stub(manager, 'unload', Promise.resolve); + let id = 'makelogs'; return manager.reload(id).then(function () { expect(load.calledWith(id)).to.be(true); expect(unload.calledWith(id)).to.be(true); @@ -56,9 +56,9 @@ describe('scenario manager', function () { }); it('should load if the index does not exist', function () { - var load = sinon.stub(manager, 'load', Promise.resolve); - var throwError = sinon.stub(manager.client, 'count', Promise.reject); - var id = 'makelogs'; + let load = sinon.stub(manager, 'load', Promise.resolve); + let throwError = sinon.stub(manager.client, 'count', Promise.reject); + let id = 'makelogs'; return manager.loadIfEmpty(id).then(function () { expect(load.calledWith(id)).to.be(true); @@ -68,13 +68,13 @@ describe('scenario manager', function () { }); it('should load if the index is empty', function () { - var load = sinon.stub(manager, 'load', Promise.resolve); - var returnZero = sinon.stub(manager.client, 'count', function () { + let load = sinon.stub(manager, 'load', Promise.resolve); + let returnZero = sinon.stub(manager.client, 'count', function () { return Promise.resolve({ 'count': 0 }); }); - var id = 'makelogs'; + let id = 'makelogs'; return manager.loadIfEmpty(id).then(function () { expect(load.calledWith(id)).to.be(true); @@ -85,13 +85,13 @@ describe('scenario manager', function () { it('should not load if the index is not empty', function () { - var load = sinon.stub(manager, 'load', Promise.resolve); - var returnOne = sinon.stub(manager.client, 'count', function () { + let load = sinon.stub(manager, 'load', Promise.resolve); + let returnOne = sinon.stub(manager.client, 'count', function () { return Promise.resolve({ 'count': 1 }); }); - var id = 'makelogs'; + let id = 'makelogs'; return manager.loadIfEmpty(id).then(function () { expect(load.called).to.be(false); diff --git a/test/fixtures/config.js b/test/fixtures/config.js index b9acf71b8e1cc..911d6caa74dcd 100644 --- a/test/fixtures/config.js +++ b/test/fixtures/config.js @@ -1,5 +1,5 @@ -var path = require('path'); -var rootDir = path.join(__dirname, 'scenarios'); +let path = require('path'); +let rootDir = path.join(__dirname, 'scenarios'); module.exports = { scenarios: { diff --git a/test/fixtures/scenario_manager.js b/test/fixtures/scenario_manager.js index d4f071358d369..24965de1b2b29 100644 --- a/test/fixtures/scenario_manager.js +++ b/test/fixtures/scenario_manager.js @@ -1,7 +1,7 @@ -var path = require('path'); -var elasticsearch = require('elasticsearch'); -var Promise = require('bluebird'); -var config = require('./config').scenarios; +let path = require('path'); +let elasticsearch = require('elasticsearch'); +let Promise = require('bluebird'); +let config = require('./config').scenarios; function ScenarioManager(server) { if (!server) throw new Error('No server defined'); @@ -23,14 +23,14 @@ function ScenarioManager(server) { * @return {Promise} A promise that is resolved when elasticsearch has a response */ ScenarioManager.prototype.load = function (id) { - var self = this; - var scenario = config[id]; + let self = this; + let scenario = config[id]; if (!scenario) return Promise.reject('No scenario found for ' + id); return Promise.all(scenario.bulk.map(function mapBulk(bulk) { - var loadIndexDefinition; + let loadIndexDefinition; if (bulk.indexDefinition) { - var body = require(path.join(scenario.baseDir, bulk.indexDefinition)); + let body = require(path.join(scenario.baseDir, bulk.indexDefinition)); loadIndexDefinition = self.client.indices.create({ index: bulk.indexName, body: body @@ -41,7 +41,7 @@ ScenarioManager.prototype.load = function (id) { return loadIndexDefinition .then(function bulkRequest() { - var body = require(path.join(scenario.baseDir, bulk.source)); + let body = require(path.join(scenario.baseDir, bulk.source)); return self.client.bulk({ body: body }); @@ -71,10 +71,10 @@ ScenarioManager.prototype.load = function (id) { * @return {Promise} A promise that is resolved when elasticsearch has a response */ ScenarioManager.prototype.unload = function (id) { - var scenario = config[id]; + let scenario = config[id]; if (!scenario) return Promise.reject('No scenario found for ' + id); - var indices = scenario.bulk.map(function mapBulk(bulk) { + let indices = scenario.bulk.map(function mapBulk(bulk) { return bulk.indexName; }); @@ -96,7 +96,7 @@ ScenarioManager.prototype.unload = function (id) { * @return {Promise} A promise that is resolved when elasticsearch has a response */ ScenarioManager.prototype.reload = function (id) { - var self = this; + let self = this; return self.unload(id) .then(function load() { @@ -120,12 +120,12 @@ ScenarioManager.prototype.deleteAll = function () { * @return {Promise} A promise that is resolved when elasticsearch has a response */ ScenarioManager.prototype.loadIfEmpty = function (id) { - var self = this; - var scenario = config[id]; + let self = this; + let scenario = config[id]; if (!scenario) throw new Error('No scenario found for ' + id); return Promise.all(scenario.bulk.map(function mapBulk(bulk) { - var loadIndexDefinition; + let loadIndexDefinition; return self.client.count({ index: bulk.indexName diff --git a/test/functional/apps/dashboard/_dashboard.js b/test/functional/apps/dashboard/_dashboard.js index 3efe4906ec4d1..0e66bea7b8825 100644 --- a/test/functional/apps/dashboard/_dashboard.js +++ b/test/functional/apps/dashboard/_dashboard.js @@ -13,7 +13,7 @@ import PageObjects from '../../../support/page_objects'; bdd.describe('dashboard tab', function describeIndexTests() { bdd.before(function () { PageObjects.common.debug('Starting dashboard before method'); - var logstash = scenarioManager.loadIfEmpty('logstashFunctional'); + let logstash = scenarioManager.loadIfEmpty('logstashFunctional'); // delete .kibana index and update configDoc return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'}) // and load a set of makelogs data @@ -32,7 +32,7 @@ bdd.describe('dashboard tab', function describeIndexTests() { }); bdd.describe('add visualizations to dashboard', function dashboardTest() { - var visualizations = ['Visualization漢字 AreaChart', + let visualizations = ['Visualization漢字 AreaChart', 'Visualization☺漢字 DataTable', 'Visualization漢字 LineChart', 'Visualization PieChart', @@ -61,8 +61,8 @@ bdd.describe('dashboard tab', function describeIndexTests() { }); bdd.it('set the timepicker time to that which contains our test data', function setTimepicker() { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; // .then(function () { PageObjects.common.debug('Set absolute time range from \"' + fromTime + '\" to \"' + toTime + '\"'); @@ -111,7 +111,7 @@ bdd.describe('dashboard tab', function describeIndexTests() { }); bdd.it('should have all the expected initial sizes', function checkVisualizationSizes() { - var visObjects = [ { dataCol: '1', dataRow: '1', dataSizeX: '3', dataSizeY: '2', title: 'Visualization漢字 AreaChart' }, + let visObjects = [ { dataCol: '1', dataRow: '1', dataSizeX: '3', dataSizeY: '2', title: 'Visualization漢字 AreaChart' }, { dataCol: '4', dataRow: '1', dataSizeX: '3', dataSizeY: '2', title: 'Visualization☺漢字 DataTable' }, { dataCol: '7', dataRow: '1', dataSizeX: '3', dataSizeY: '2', title: 'Visualization漢字 LineChart' }, { dataCol: '10', dataRow: '1', dataSizeX: '3', dataSizeY: '2', title: 'Visualization PieChart' }, diff --git a/test/functional/apps/discover/_collapse_expand.js b/test/functional/apps/discover/_collapse_expand.js index 3eaf45e83144b..4b8b04eb78ef7 100644 --- a/test/functional/apps/discover/_collapse_expand.js +++ b/test/functional/apps/discover/_collapse_expand.js @@ -12,8 +12,8 @@ import PageObjects from '../../../support/page_objects'; bdd.describe('discover tab', function describeIndexTests() { bdd.before(function () { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; // delete .kibana index and update configDoc return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'}) diff --git a/test/functional/apps/discover/_field_data.js b/test/functional/apps/discover/_field_data.js index 5123a54178cc8..35a33bdd331b3 100644 --- a/test/functional/apps/discover/_field_data.js +++ b/test/functional/apps/discover/_field_data.js @@ -12,8 +12,8 @@ import PageObjects from '../../../support/page_objects'; bdd.describe('discover app', function describeIndexTests() { bdd.before(function () { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; // delete .kibana index and update configDoc return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'}) @@ -37,12 +37,12 @@ bdd.describe('discover app', function describeIndexTests() { bdd.describe('field data', function () { - var queryName1 = 'Query # 1'; - var fromTimeString = 'September 19th 2015, 06:31:44.000'; - var toTimeString = 'September 23rd 2015, 18:31:44.000'; + let queryName1 = 'Query # 1'; + let fromTimeString = 'September 19th 2015, 06:31:44.000'; + let toTimeString = 'September 23rd 2015, 18:31:44.000'; bdd.it('search php should show the correct hit count', function () { - var expectedHitCount = '445'; + let expectedHitCount = '445'; return PageObjects.discover.query('php') .then(function () { return PageObjects.common.try(function tryingForTime() { @@ -65,7 +65,7 @@ bdd.describe('discover app', function describeIndexTests() { }); bdd.it('search _type:apache should show the correct hit count', function () { - var expectedHitCount = '11,156'; + let expectedHitCount = '11,156'; return PageObjects.discover.query('_type:apache') .then(function () { return PageObjects.common.try(function tryingForTime() { @@ -78,7 +78,7 @@ bdd.describe('discover app', function describeIndexTests() { }); bdd.it('doc view should show Time and _source columns', function () { - var expectedHeader = 'Time _source'; + let expectedHeader = 'Time _source'; return PageObjects.discover.getDocHeader() .then(function (header) { expect(header).to.be(expectedHeader); @@ -87,7 +87,7 @@ bdd.describe('discover app', function describeIndexTests() { bdd.it('doc view should show oldest time first', function () { // Note: Could just check the timestamp, but might as well check that the whole doc is as expected. - var ExpectedDoc = + let ExpectedDoc = 'September 22nd 2015, 23:50:13.253 index:logstash-2015.09.22 @timestamp:September 22nd 2015, 23:50:13.253' + ' ip:238.171.34.42 extension:jpg response:200 geo.coordinates:{ "lat": 38.66494528, "lon": -88.45299556' + ' } geo.src:FR geo.dest:KH geo.srcdest:FR:KH @tags:success, info utc_time:September 22nd 2015,' @@ -138,7 +138,7 @@ bdd.describe('discover app', function describeIndexTests() { bdd.it('doc view should sort ascending', function () { // Note: Could just check the timestamp, but might as well check that the whole doc is as expected. - var ExpectedDoc = + let ExpectedDoc = 'September 20th 2015, 00:00:00.000 index:logstash-2015.09.20 @timestamp:September 20th 2015, 00:00:00.000' + ' ip:143.84.142.7 extension:jpg response:200 geo.coordinates:{ "lat": 38.68407028, "lon": -120.9871642 }' + ' geo.src:ES geo.dest:US geo.srcdest:ES:US @tags:error, info utc_time:September 20th 2015, 00:00:00.000' @@ -230,8 +230,8 @@ bdd.describe('discover app', function describeIndexTests() { bdd.it('a bad syntax query should show an error message', function () { - var expectedHitCount = '1011,156'; - var expectedError = 'Discover: Failed to parse query [xxx(yyy]'; + let expectedHitCount = '1011,156'; + let expectedError = 'Discover: Failed to parse query [xxx(yyy]'; return PageObjects.discover.query('xxx(yyy') .then(function () { return PageObjects.header.getToastMessage(); diff --git a/test/functional/apps/discover/_shared_links.js b/test/functional/apps/discover/_shared_links.js index 899d050fbd286..398ac194b4898 100644 --- a/test/functional/apps/discover/_shared_links.js +++ b/test/functional/apps/discover/_shared_links.js @@ -11,12 +11,12 @@ import { import PageObjects from '../../../support/page_objects'; bdd.describe('shared links', function describeIndexTests() { - var baseUrl; + let baseUrl; // The message changes for Firefox < 41 and Firefox >= 41 // var expectedToastMessage = 'Share search: URL selected. Press Ctrl+C to copy.'; // var expectedToastMessage = 'Share search: URL copied to clipboard.'; // Pass either one. - var expectedToastMessage = /Share search: URL (selected\. Press Ctrl\+C to copy\.|copied to clipboard\.)/; + let expectedToastMessage = /Share search: URL (selected\. Press Ctrl\+C to copy\.|copied to clipboard\.)/; bdd.before(function () { baseUrl = PageObjects.common.getHostPort(); @@ -26,8 +26,8 @@ bdd.describe('shared links', function describeIndexTests() { baseUrl = baseUrl.replace(':80','').replace(':443',''); PageObjects.common.debug('New baseUrl = ' + baseUrl); - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; // delete .kibana index and update configDoc return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'}) @@ -57,7 +57,7 @@ bdd.describe('shared links', function describeIndexTests() { bdd.describe('shared link', function () { bdd.it('should show "Share a link" caption', function () { - var expectedCaption = 'Share saved'; + let expectedCaption = 'Share saved'; return PageObjects.discover.clickShare() .then(function () { PageObjects.common.saveScreenshot('Discover-share-link'); @@ -69,7 +69,7 @@ bdd.describe('shared links', function describeIndexTests() { }); bdd.it('should show the correct formatted URL', function () { - var expectedUrl = baseUrl + let expectedUrl = baseUrl + '/app/kibana?_t=1453775307251#' + '/discover?_g=(refreshInterval:(display:Off,pause:!f,value:0),time' + ':(from:\'2015-09-19T06:31:44.000Z\',mode:absolute,to:\'2015-09' @@ -100,7 +100,7 @@ bdd.describe('shared links', function describeIndexTests() { // TODO: verify clipboard contents bdd.it('shorten URL button should produce a short URL', function () { - var re = new RegExp(baseUrl + '/goto/[0-9a-f]{32}$'); + let re = new RegExp(baseUrl + '/goto/[0-9a-f]{32}$'); return PageObjects.discover.clickShortenUrl() .then(function () { return PageObjects.common.try(function tryingForTime() { diff --git a/test/functional/apps/discover/_source_filters.js b/test/functional/apps/discover/_source_filters.js index 563d638ceb06f..4530b9061a882 100644 --- a/test/functional/apps/discover/_source_filters.js +++ b/test/functional/apps/discover/_source_filters.js @@ -7,13 +7,13 @@ import { import PageObjects from '../../../support/page_objects'; -var expect = require('expect.js'); +let expect = require('expect.js'); bdd.describe('source filters', function describeIndexTests() { bdd.before(function () { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; // delete .kibana index and update configDoc return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'}) diff --git a/test/functional/apps/management/_creation_form_changes.js b/test/functional/apps/management/_creation_form_changes.js index b94473a5018a2..19b10ed069f10 100644 --- a/test/functional/apps/management/_creation_form_changes.js +++ b/test/functional/apps/management/_creation_form_changes.js @@ -22,7 +22,7 @@ bdd.describe('user input reactions', function () { }); bdd.it('should hide time-based index pattern when time-based option is unchecked', function () { - var self = this; + let self = this; return PageObjects.settings.getTimeBasedEventsCheckbox() .then(function (selected) { // uncheck the 'time-based events' checkbox @@ -30,14 +30,14 @@ bdd.describe('user input reactions', function () { }) // try to find the checkbox (this shouldn fail) .then(function () { - var waitTime = 10000; + let waitTime = 10000; return PageObjects.settings.getTimeBasedIndexPatternCheckbox(waitTime); }) .then(function () { PageObjects.common.saveScreenshot('Settings-indices-hide-time-based-index-pattern'); // we expect the promise above to fail - var handler = PageObjects.common.createErrorHandler(self); - var msg = 'Found time based index pattern checkbox'; + let handler = PageObjects.common.createErrorHandler(self); + let msg = 'Found time based index pattern checkbox'; handler(msg); }) .catch(function () { diff --git a/test/functional/apps/management/_index_pattern_create_delete.js b/test/functional/apps/management/_index_pattern_create_delete.js index db6c07079d4c3..b9e1ac5a1522d 100644 --- a/test/functional/apps/management/_index_pattern_create_delete.js +++ b/test/functional/apps/management/_index_pattern_create_delete.js @@ -48,7 +48,7 @@ bdd.describe('creating and deleting default index', function describeIndexTests( return PageObjects.settings.getTableHeader() .then(function (headers) { PageObjects.common.debug('header.length = ' + headers.length); - var expectedHeaders = [ + let expectedHeaders = [ 'name', 'type', 'format', @@ -61,7 +61,7 @@ bdd.describe('creating and deleting default index', function describeIndexTests( expect(headers.length).to.be(expectedHeaders.length); - var comparedHeaders = headers.map(function compareHead(header, i) { + let comparedHeaders = headers.map(function compareHead(header, i) { return header.getVisibleText() .then(function (text) { expect(text).to.be(expectedHeaders[i]); @@ -75,7 +75,7 @@ bdd.describe('creating and deleting default index', function describeIndexTests( bdd.describe('index pattern deletion', function indexDelete() { bdd.before(function () { - var expectedAlertText = 'Are you sure you want to remove this index pattern?'; + let expectedAlertText = 'Are you sure you want to remove this index pattern?'; return PageObjects.settings.removeIndexPattern() .then(function (alertText) { PageObjects.common.saveScreenshot('Settings-indices-confirm-remove-index-pattern'); diff --git a/test/functional/apps/management/_index_pattern_popularity.js b/test/functional/apps/management/_index_pattern_popularity.js index dda2748db24b6..742e0bd33e0ab 100644 --- a/test/functional/apps/management/_index_pattern_popularity.js +++ b/test/functional/apps/management/_index_pattern_popularity.js @@ -27,7 +27,7 @@ bdd.describe('index result popularity', function describeIndexTests() { }); bdd.describe('change popularity', function indexPatternCreation() { - var fieldName = 'geo.coordinates'; + let fieldName = 'geo.coordinates'; // set the page size to All again, https://github.com/elastic/kibana/issues/5030 // TODO: remove this after issue #5030 is closed diff --git a/test/functional/apps/management/_index_pattern_results_sort.js b/test/functional/apps/management/_index_pattern_results_sort.js index 82d37495ef23e..23258bbacf84f 100644 --- a/test/functional/apps/management/_index_pattern_results_sort.js +++ b/test/functional/apps/management/_index_pattern_results_sort.js @@ -16,7 +16,7 @@ bdd.describe('index result field sort', function describeIndexTests() { return esClient.deleteAndUpdateConfigDoc(); }); - var columns = [{ + let columns = [{ heading: 'name', first: '@message', last: 'xss.raw', diff --git a/test/functional/apps/management/_initial_state.js b/test/functional/apps/management/_initial_state.js index edca2e6eb7bca..cd84c13013f79 100644 --- a/test/functional/apps/management/_initial_state.js +++ b/test/functional/apps/management/_initial_state.js @@ -37,7 +37,7 @@ bdd.describe('initial state', function () { }); bdd.it('should contain default index pattern', function () { - var defaultPattern = 'logstash-*'; + let defaultPattern = 'logstash-*'; return PageObjects.settings.getIndexPatternField().getProperty('value') .then(function (pattern) { diff --git a/test/functional/apps/visualize/_area_chart.js b/test/functional/apps/visualize/_area_chart.js index d431b3e2cfd79..07a817d3ae21b 100644 --- a/test/functional/apps/visualize/_area_chart.js +++ b/test/functional/apps/visualize/_area_chart.js @@ -10,8 +10,8 @@ import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { bdd.before(function () { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; PageObjects.common.debug('navigateToApp visualize'); return PageObjects.common.navigateToApp('visualize') @@ -60,7 +60,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.describe('area charts', function indexPatternCreation() { - var vizName1 = 'Visualization AreaChart'; + let vizName1 = 'Visualization AreaChart'; bdd.it('should save and load with special characters', function () { const vizNamewithSpecialChars = vizName1 + '/?&=%'; @@ -109,12 +109,12 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show correct chart, take screenshot', function () { - var chartHeight = 0; - var xAxisLabels = [ '2015-09-20 00:00', '2015-09-21 00:00', + let chartHeight = 0; + let xAxisLabels = [ '2015-09-20 00:00', '2015-09-21 00:00', '2015-09-22 00:00', '2015-09-23 00:00' ]; - var yAxisLabels = ['0','200','400','600','800','1,000','1,200','1,400','1,600']; - var expectedAreaChartData = [37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, + let yAxisLabels = ['0','200','400','600','800','1,000','1,200','1,400','1,600']; + let expectedAreaChartData = [37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, 1361, 1415, 707, 177, 27, 32, 175, 707, 1408, 1355, 726, 201, 29 ]; @@ -144,7 +144,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show correct data', function () { - var expectedTableData = [ 'September 20th 2015, 00:00:00.000 37', + let expectedTableData = [ 'September 20th 2015, 00:00:00.000 37', 'September 20th 2015, 03:00:00.000 202', 'September 20th 2015, 06:00:00.000 740', 'September 20th 2015, 09:00:00.000 1,437', diff --git a/test/functional/apps/visualize/_chart_types.js b/test/functional/apps/visualize/_chart_types.js index 081f1a3b01e66..b845f467ef302 100644 --- a/test/functional/apps/visualize/_chart_types.js +++ b/test/functional/apps/visualize/_chart_types.js @@ -17,7 +17,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.describe('chart types', function indexPatternCreation() { bdd.it('should show the correct chart types', function () { - var expectedChartTypes = [ + let expectedChartTypes = [ 'Area chart', 'Data table', 'Line chart', 'Markdown widget', 'Metric', 'Pie chart', 'Tile map', 'Timeseries', 'Vertical bar chart' ]; diff --git a/test/functional/apps/visualize/_data_table.js b/test/functional/apps/visualize/_data_table.js index 1ec25f0006b2f..4c7681dff58aa 100644 --- a/test/functional/apps/visualize/_data_table.js +++ b/test/functional/apps/visualize/_data_table.js @@ -9,8 +9,8 @@ import { import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; bdd.before(function () { PageObjects.common.debug('navigateToApp visualize'); @@ -52,7 +52,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.describe('data table', function indexPatternCreation() { - var vizName1 = 'Visualization DataTable'; + let vizName1 = 'Visualization DataTable'; bdd.it('should be able to save and load', function () { return PageObjects.visualize.saveVisualization(vizName1) @@ -72,8 +72,8 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show correct data, take screenshot', function () { - var chartHeight = 0; - var expectedChartData = [ '0 2,088', '2,000 2,748', '4,000 2,707', '6,000 2,876', + let chartHeight = 0; + let expectedChartData = [ '0 2,088', '2,000 2,748', '4,000 2,707', '6,000 2,876', '8,000 2,863', '10,000 147', '12,000 148', '14,000 129', '16,000 161', '18,000 137' ]; diff --git a/test/functional/apps/visualize/_line_chart.js b/test/functional/apps/visualize/_line_chart.js index a17efaa1cd1b9..b03ecaef013bd 100644 --- a/test/functional/apps/visualize/_line_chart.js +++ b/test/functional/apps/visualize/_line_chart.js @@ -10,8 +10,8 @@ import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { bdd.before(function () { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; PageObjects.common.debug('navigateToApp visualize'); return PageObjects.common.navigateToApp('visualize') @@ -51,13 +51,13 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.describe('line charts', function indexPatternCreation() { - var vizName1 = 'Visualization LineChart'; + let vizName1 = 'Visualization LineChart'; bdd.it('should show correct chart, take screenshot', function () { // this test only verifies the numerical part of this data // it could also check the legend to verify the extensions - var expectedChartData = ['jpg 9,109', 'css 2,159', 'png 1,373', 'gif 918', 'php 445']; + let expectedChartData = ['jpg 9,109', 'css 2,159', 'png 1,373', 'gif 918', 'php 445']; // sleep a bit before trying to get the chart data return PageObjects.common.sleep(3000) @@ -66,8 +66,8 @@ bdd.describe('visualize app', function describeIndexTests() { .then(function showData(data) { PageObjects.common.debug('data=' + data); PageObjects.common.saveScreenshot('Visualize-line-chart'); - var tolerance = 10; // the y-axis scale is 10000 so 10 is 0.1% - for (var x = 0; x < data.length; x++) { + let tolerance = 10; // the y-axis scale is 10000 so 10 is 0.1% + for (let x = 0; x < data.length; x++) { PageObjects.common.debug('x=' + x + ' expectedChartData[x].split(\' \')[1] = ' + (expectedChartData[x].split(' ')[1]).replace(',', '') + ' data[x]=' + data[x] + ' diff=' + Math.abs(expectedChartData[x].split(' ')[1].replace(',', '') - data[x])); @@ -83,7 +83,7 @@ bdd.describe('visualize app', function describeIndexTests() { // this test only verifies the numerical part of this data // https://github.com/elastic/kibana/issues/8141 - var expectedChartData = ['png 1,373', 'php 445', 'jpg 9,109', 'gif 918', 'css 2,159']; + let expectedChartData = ['png 1,373', 'php 445', 'jpg 9,109', 'gif 918', 'css 2,159']; PageObjects.common.debug('Order By = Term'); return PageObjects.visualize.selectOrderBy('_term') @@ -96,8 +96,8 @@ bdd.describe('visualize app', function describeIndexTests() { .then(function showData(data) { PageObjects.common.debug('data=' + data); PageObjects.common.saveScreenshot('Visualize-line-chart'); - var tolerance = 10; // the y-axis scale is 10000 so 10 is 0.1% - for (var x = 0; x < data.length; x++) { + let tolerance = 10; // the y-axis scale is 10000 so 10 is 0.1% + for (let x = 0; x < data.length; x++) { PageObjects.common.debug('x=' + x + ' expectedChartData[x].split(\' \')[1] = ' + (expectedChartData[x].split(' ')[1]).replace(',', '') + ' data[x]=' + data[x] + ' diff=' + Math.abs(expectedChartData[x].split(' ')[1].replace(',', '') - data[x])); @@ -112,7 +112,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.it('should show correct data, ordered by Term', function () { - var expectedChartData = ['png 1,373', 'php 445', 'jpg 9,109', 'gif 918', 'css 2,159']; + let expectedChartData = ['png 1,373', 'php 445', 'jpg 9,109', 'gif 918', 'css 2,159']; return PageObjects.visualize.collapseChart() .then(function getDataTableData() { diff --git a/test/functional/apps/visualize/_metric_chart.js b/test/functional/apps/visualize/_metric_chart.js index ff67bfcc6b507..37eb0b53467f1 100644 --- a/test/functional/apps/visualize/_metric_chart.js +++ b/test/functional/apps/visualize/_metric_chart.js @@ -9,8 +9,8 @@ import { import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; bdd.before(function () { PageObjects.common.debug('navigateToApp visualize'); @@ -31,7 +31,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.describe('metric chart', function indexPatternCreation() { bdd.it('should show Count', function () { - var expectedCount = ['14,004', 'Count']; + let expectedCount = ['14,004', 'Count']; // initial metric of "Count" is selected by default return PageObjects.common.try(function tryingForTime() { @@ -44,7 +44,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Average', function () { - var avgMachineRam = ['13,104,036,080.615', 'Average machine.ram']; + let avgMachineRam = ['13,104,036,080.615', 'Average machine.ram']; return PageObjects.visualize.clickMetricEditor() .then(function () { PageObjects.common.debug('Aggregation = Average'); @@ -68,7 +68,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Sum', function () { - var sumPhpMemory = ['85,865,880', 'Sum of phpmemory']; + let sumPhpMemory = ['85,865,880', 'Sum of phpmemory']; PageObjects.common.debug('Aggregation = Sum'); return PageObjects.visualize.selectAggregation('Sum') .then(function selectField() { @@ -89,7 +89,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Median', function () { - var medianBytes = ['5,565.263', '50th percentile of bytes']; + let medianBytes = ['5,565.263', '50th percentile of bytes']; // For now, only comparing the text label part of the metric PageObjects.common.debug('Aggregation = Median'); return PageObjects.visualize.selectAggregation('Median') @@ -112,7 +112,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Min', function () { - var minTimestamp = ['September 20th 2015, 00:00:00.000', 'Min @timestamp']; + let minTimestamp = ['September 20th 2015, 00:00:00.000', 'Min @timestamp']; PageObjects.common.debug('Aggregation = Min'); return PageObjects.visualize.selectAggregation('Min') .then(function selectField() { @@ -133,7 +133,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Max', function () { - var maxRelatedContentArticleModifiedTime = ['April 4th 2015, 00:54:41.000', 'Max relatedContent.article:modified_time']; + let maxRelatedContentArticleModifiedTime = ['April 4th 2015, 00:54:41.000', 'Max relatedContent.article:modified_time']; PageObjects.common.debug('Aggregation = Max'); return PageObjects.visualize.selectAggregation('Max') .then(function selectField() { @@ -154,7 +154,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Standard Deviation', function () { - var standardDeviationBytes = [ + let standardDeviationBytes = [ '-1,435.138', 'Lower Standard Deviation of bytes', '12,889.766', 'Upper Standard Deviation of bytes' ]; @@ -178,7 +178,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Unique Count', function () { - var uniqueCountClientip = ['1,000', 'Unique count of clientip']; + let uniqueCountClientip = ['1,000', 'Unique count of clientip']; PageObjects.common.debug('Aggregation = Unique Count'); return PageObjects.visualize.selectAggregation('Unique Count') .then(function selectField() { @@ -206,7 +206,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Percentiles', function () { - var percentileMachineRam = [ + let percentileMachineRam = [ '2,147,483,648', '1st percentile of machine.ram', '3,221,225,472', '5th percentile of machine.ram', '7,516,192,768', '25th percentile of machine.ram', @@ -236,7 +236,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show Percentile Ranks', function () { - var percentileRankBytes = [ '2.036%', 'Percentile rank 99 of "memory"']; + let percentileRankBytes = [ '2.036%', 'Percentile rank 99 of "memory"']; PageObjects.common.debug('Aggregation = Percentile Ranks'); return PageObjects.visualize.selectAggregation('Percentile Ranks') .then(function selectField() { diff --git a/test/functional/apps/visualize/_pie_chart.js b/test/functional/apps/visualize/_pie_chart.js index 0c71c47c0892d..636c7003008f8 100644 --- a/test/functional/apps/visualize/_pie_chart.js +++ b/test/functional/apps/visualize/_pie_chart.js @@ -10,8 +10,8 @@ import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { bdd.before(function () { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; PageObjects.common.debug('navigateToApp visualize'); return PageObjects.common.navigateToApp('visualize') @@ -59,7 +59,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.describe('pie chart', function indexPatternCreation() { - var vizName1 = 'Visualization PieChart'; + let vizName1 = 'Visualization PieChart'; bdd.it('should save and load', function () { return PageObjects.visualize.saveVisualization(vizName1) @@ -83,11 +83,11 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show 10 slices in pie chart, take screenshot', function () { - var expectedPieChartSliceCount = 10; + let expectedPieChartSliceCount = 10; return PageObjects.visualize.getPieChartData() .then(function (pieData) { - var barHeightTolerance = 1; + let barHeightTolerance = 1; PageObjects.common.debug('pieData.length = ' + pieData.length); PageObjects.common.saveScreenshot('Visualize-pie-chart'); expect(pieData.length).to.be(expectedPieChartSliceCount); @@ -95,7 +95,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show correct data', function () { - var expectedTableData = [ '0 55', '40,000 50', '80,000 41', '120,000 43', + let expectedTableData = [ '0 55', '40,000 50', '80,000 41', '120,000 43', '160,000 44', '200,000 40', '240,000 46', '280,000 39', '320,000 40', '360,000 47' ]; diff --git a/test/functional/apps/visualize/_tile_map.js b/test/functional/apps/visualize/_tile_map.js index 6d055f377009a..8959590497c95 100644 --- a/test/functional/apps/visualize/_tile_map.js +++ b/test/functional/apps/visualize/_tile_map.js @@ -9,8 +9,8 @@ import { import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; bdd.before(function () { @@ -52,7 +52,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.describe('tile map chart', function indexPatternCreation() { bdd.it('should show correct tile map data on default zoom level', function () { - var expectedTableData = [ 'dn 1,429', 'dp 1,418', '9y 1,215', '9z 1,099', 'dr 1,076', + let expectedTableData = [ 'dn 1,429', 'dp 1,418', '9y 1,215', '9z 1,099', 'dr 1,076', 'dj 982', '9v 938', '9q 722', '9w 475', 'cb 457', 'c2 453', '9x 420', 'dq 399', '9r 396', '9t 274', 'c8 271', 'dh 214', 'b6 207', 'bd 206', 'b7 167', 'f0 141', 'be 128', '9m 126', 'bf 85', 'de 73', 'bg 71', '9p 71', 'c1 57', 'c4 50', '9u 48', @@ -75,7 +75,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.it('should zoom out to level 1 from default level 2', function () { - var expectedPrecision2Circles = [ { color: '#750000', radius: 48 }, + let expectedPrecision2Circles = [ { color: '#750000', radius: 48 }, { color: '#750000', radius: 48 }, { color: '#750000', radius: 44 }, { color: '#a40000', radius: 42 }, @@ -143,7 +143,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('Fit data bounds should zoom to level 3', function () { - var expectedPrecision2ZoomCircles = [ { color: '#750000', radius: 192 }, + let expectedPrecision2ZoomCircles = [ { color: '#750000', radius: 192 }, { color: '#750000', radius: 191 }, { color: '#750000', radius: 177 }, { color: '#a40000', radius: 168 }, @@ -206,12 +206,12 @@ bdd.describe('visualize app', function describeIndexTests() { ** changed, then open the saved viz and check that it's back to the original data. */ bdd.it('should save with zoom level and load, take screenshot', function () { - var vizName1 = 'Visualization TileMap'; - var expectedTableData = [ 'dr4 127', 'dr7 92', '9q5 91', '9qc 89', 'drk 87', + let vizName1 = 'Visualization TileMap'; + let expectedTableData = [ 'dr4 127', 'dr7 92', '9q5 91', '9qc 89', 'drk 87', 'dps 82', 'dph 82', 'dp3 79', 'dpe 78', 'dp8 77' ]; - var expectedTableDataZoomed = [ 'dr5r 21', 'dps8 20', '9q5b 19', 'b6uc 17', + let expectedTableDataZoomed = [ 'dr5r 21', 'dps8 20', '9q5b 19', 'b6uc 17', '9y63 17', 'c20g 16', 'dqfz 15', 'dr8h 14', 'dp8p 14', 'dp3k 14' ]; diff --git a/test/functional/apps/visualize/_vertical_bar_chart.js b/test/functional/apps/visualize/_vertical_bar_chart.js index 1fdaf23603ee6..e718be79bb931 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart.js +++ b/test/functional/apps/visualize/_vertical_bar_chart.js @@ -9,8 +9,8 @@ import { import PageObjects from '../../../support/page_objects'; bdd.describe('visualize app', function describeIndexTests() { - var fromTime = '2015-09-19 06:31:44.000'; - var toTime = '2015-09-23 18:31:44.000'; + let fromTime = '2015-09-19 06:31:44.000'; + let toTime = '2015-09-23 18:31:44.000'; bdd.before(function () { PageObjects.common.debug('navigateToApp visualize'); @@ -51,7 +51,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.describe('vertical bar chart', function indexPatternCreation() { - var vizName1 = 'Visualization VerticalBarChart'; + let vizName1 = 'Visualization VerticalBarChart'; bdd.it('should save and load', function () { return PageObjects.visualize.saveVisualization(vizName1) @@ -74,7 +74,7 @@ bdd.describe('visualize app', function describeIndexTests() { }); bdd.it('should show correct chart, take screenshot', function () { - var expectedChartValues = [37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, + let expectedChartValues = [37, 202, 740, 1437, 1371, 751, 188, 31, 42, 202, 683, 1361, 1415, 707, 177, 27, 32, 175, 707, 1408, 1355, 726, 201, 29 ]; @@ -96,7 +96,7 @@ bdd.describe('visualize app', function describeIndexTests() { bdd.it('should show correct data', function () { // this is only the first page of the tabular data. - var expectedChartData = [ 'September 20th 2015, 00:00:00.000 37', + let expectedChartData = [ 'September 20th 2015, 00:00:00.000 37', 'September 20th 2015, 03:00:00.000 202', 'September 20th 2015, 06:00:00.000 740', 'September 20th 2015, 09:00:00.000 1,437', diff --git a/test/functional/apps/visualize/index.js b/test/functional/apps/visualize/index.js index bc13a824148a6..11d25a384ba1e 100644 --- a/test/functional/apps/visualize/index.js +++ b/test/functional/apps/visualize/index.js @@ -19,7 +19,7 @@ bdd.describe('visualize app', function () { remote.setWindowSize(1280,800); PageObjects.common.debug('Starting visualize before method'); - var logstash = scenarioManager.loadIfEmpty('logstashFunctional'); + let logstash = scenarioManager.loadIfEmpty('logstashFunctional'); // delete .kibana index and update configDoc return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'}) .then(function loadkibanaIndexPattern() { diff --git a/test/functional/status_page/index.js b/test/functional/status_page/index.js index afe34c9a947b2..d1f6f0b37c5ae 100644 --- a/test/functional/status_page/index.js +++ b/test/functional/status_page/index.js @@ -4,7 +4,7 @@ import { import PageObjects from '../../support/page_objects'; -var expect = require('expect.js'); +let expect = require('expect.js'); bdd.describe('status page', function () { bdd.before(function () { @@ -12,7 +12,7 @@ bdd.describe('status page', function () { }); bdd.it('should show the kibana plugin as ready', function () { - var self = this; + let self = this; return PageObjects.common.tryForTime(6000, function () { return PageObjects.common.findTestSubject('statusBreakdown') diff --git a/test/mocha_setup.js b/test/mocha_setup.js index ea24360a11832..24acc31cefd35 100644 --- a/test/mocha_setup.js +++ b/test/mocha_setup.js @@ -1,5 +1,5 @@ -var sinon = require('sinon'); -var autoRelease = require('auto-release-sinon'); +let sinon = require('sinon'); +let autoRelease = require('auto-release-sinon'); require('babel/register')(require('../src/optimize/babel_options').node); @@ -13,7 +13,7 @@ require('babel/register')(require('../src/optimize/babel_options').node); // The global "afterEach" variable is also tracked, and once it is assigned by mocha // the variable global is reconfigured to point directly to the new value (from mocha) // and all of the queued invocations are executed. -var queuedAfterEachArgs = []; +let queuedAfterEachArgs = []; Object.defineProperty(global, 'afterEach', { configurable: true, get() { return undefined; }, diff --git a/test/server_config.js b/test/server_config.js index 97ecf228f0914..5bffc4acd1be3 100644 --- a/test/server_config.js +++ b/test/server_config.js @@ -1,6 +1,6 @@ -var shield = require('./shield'); +let shield = require('./shield'); -var kibanaURL = '/app/kibana'; +let kibanaURL = '/app/kibana'; module.exports = { servers: { diff --git a/test/support/env_setup.js b/test/support/env_setup.js index 0ced6024f85bb..25683e344da0d 100644 --- a/test/support/env_setup.js +++ b/test/support/env_setup.js @@ -1,4 +1,4 @@ -var defaults = require('lodash').defaults; +let defaults = require('lodash').defaults; const babelOptions = require('../../src/optimize/babel_options'); require('source-map-support').install(); diff --git a/test/support/page_objects/common.js b/test/support/page_objects/common.js index a2c11ab47859e..aa407c9a67ea1 100644 --- a/test/support/page_objects/common.js +++ b/test/support/page_objects/common.js @@ -40,7 +40,7 @@ export default class Common { init(remote) { function injectTimestampQuery(func, url) { - var formatted = modifyQueryString(url, function (parsed) { + let formatted = modifyQueryString(url, function (parsed) { parsed.query._t = Date.now(); }); return func.call(this, formatted); @@ -56,7 +56,7 @@ export default class Common { } function modifyQueryString(url, func) { - var parsed = parse(url, true); + let parsed = parse(url, true); if (parsed.query === null) { parsed.query = {}; } @@ -81,8 +81,8 @@ export default class Common { } navigateToApp(appName, testStatusPage) { - var self = this; - var appUrl = getUrl.noAuth(config.servers.kibana, config.apps[appName]); + let self = this; + let appUrl = getUrl.noAuth(config.servers.kibana, config.apps[appName]); self.debug('navigating to ' + appName + ' url: ' + appUrl); function navigateTo(url) { @@ -116,7 +116,7 @@ export default class Common { return self.remote.getCurrentUrl(); }) .then(function (currentUrl) { - var loginPage = new RegExp('login').test(currentUrl); + let loginPage = new RegExp('login').test(currentUrl); if (loginPage) { self.debug('Found loginPage username = ' + config.servers.kibana.username); @@ -131,7 +131,7 @@ export default class Common { }) .then(function (currentUrl) { currentUrl = currentUrl.replace(/\/\/\w+:\w+@/, '//'); - var maxAdditionalLengthOnNavUrl = 230; + let maxAdditionalLengthOnNavUrl = 230; // On several test failures at the end of the TileMap test we try to navigate back to // Visualize so we can create the next Vertical Bar Chart, but we can see from the // logging and the screenshot that it's still on the TileMap page. Why didn't the "get" @@ -145,12 +145,12 @@ export default class Common { // Browsers don't show the ':port' if it's 80 or 443 so we have to // remove that part so we can get a match in the tests. - var navSuccessful = new RegExp(appUrl.replace(':80','').replace(':443','') + let navSuccessful = new RegExp(appUrl.replace(':80','').replace(':443','') + '.{0,' + maxAdditionalLengthOnNavUrl + '}$') .test(currentUrl); if (!navSuccessful) { - var msg = 'App failed to load: ' + appName + + let msg = 'App failed to load: ' + appName + ' in ' + defaultFindTimeout + 'ms' + ' appUrl = ' + appUrl + ' currentUrl = ' + currentUrl; @@ -165,7 +165,7 @@ export default class Common { return navigateTo(appUrl) .then(function (currentUrl) { - var lastUrl = currentUrl; + let lastUrl = currentUrl; return self.try(function () { // give the app time to update the URL return self.sleep(501) @@ -184,7 +184,7 @@ export default class Common { } runScript(fn, timeout) { - var self = this; + let self = this; // by default, give the app 10 seconds to load timeout = timeout || 10000; @@ -192,9 +192,9 @@ export default class Common { return self.remote .setExecuteAsyncTimeout(timeout) .executeAsync(function (done) { - var interval = setInterval(function () { - var ready = (document.readyState === 'complete'); - var hasJQuery = !!window.$; + let interval = setInterval(function () { + let ready = (document.readyState === 'complete'); + let hasJQuery = !!window.$; if (ready && hasJQuery) { console.log('doc ready, jquery loaded'); @@ -228,7 +228,7 @@ export default class Common { } sleep(sleepMilliseconds) { - var self = this; + let self = this; self.debug('... sleep(' + sleepMilliseconds + ') start'); return bluebird.resolve().delay(sleepMilliseconds) diff --git a/test/support/page_objects/dashboard_page.js b/test/support/page_objects/dashboard_page.js index 426efebee0147..44bc4bfae35c3 100644 --- a/test/support/page_objects/dashboard_page.js +++ b/test/support/page_objects/dashboard_page.js @@ -124,7 +124,7 @@ export default class DashboardPage { // use the search filter box to narrow the results down to a single // entry, or at least to a single page of results loadSavedDashboard(dashName) { - var self = this; + let self = this; return this.findTimeout .findByCssSelector('[aria-label="Open Saved Dashboard"]') .click() @@ -160,7 +160,7 @@ export default class DashboardPage { return chart.getAttribute('title'); } - var getTitlePromises = titleObjects.map(getTitles); + let getTitlePromises = titleObjects.map(getTitles); return Promise.all(getTitlePromises); }); } @@ -172,7 +172,7 @@ export default class DashboardPage { .then(function (titleObjects) { function getTitles(chart) { - var obj = {}; + let obj = {}; return chart.getAttribute('data-col') .then(theData => { obj = {dataCol:theData}; @@ -211,7 +211,7 @@ export default class DashboardPage { }); } - var getTitlePromises = titleObjects.map(getTitles); + let getTitlePromises = titleObjects.map(getTitles); return Promise.all(getTitlePromises); }); } diff --git a/test/support/page_objects/discover_page.js b/test/support/page_objects/discover_page.js index aed34e59c168b..b1dd2cb07ec2a 100644 --- a/test/support/page_objects/discover_page.js +++ b/test/support/page_objects/discover_page.js @@ -92,7 +92,7 @@ export default class DiscoverPage { .getAttribute('height'); } - var getChartDataPromises = chartData.map(getChartData); + let getChartDataPromises = chartData.map(getChartData); return Promise.all(getChartDataPromises); }) .then(function (bars) { diff --git a/test/support/page_objects/header_page.js b/test/support/page_objects/header_page.js index 3065f7b1c13f2..49d797e16c836 100644 --- a/test/support/page_objects/header_page.js +++ b/test/support/page_objects/header_page.js @@ -73,7 +73,7 @@ export default class HeaderPage { } clickGoButton() { - var self = this; + let self = this; return this.remote.setFindTimeout(defaultFindTimeout) .findByClassName('kbn-timepicker-go') .click() diff --git a/test/support/page_objects/settings_page.js b/test/support/page_objects/settings_page.js index eb3ed431ae7a9..6d4d269d42ed3 100644 --- a/test/support/page_objects/settings_page.js +++ b/test/support/page_objects/settings_page.js @@ -37,7 +37,7 @@ export default class SettingsPage { } setAdvancedSettings(propertyName, propertyValue) { - var self = this; + let self = this; return PageObjects.common.findTestSubject('advancedSetting-' + propertyName + '-editButton') .click() @@ -65,7 +65,7 @@ export default class SettingsPage { } getAdvancedSettings(propertyName) { - var self = this; + let self = this; PageObjects.common.debug('in setAdvancedSettings'); return PageObjects.common.findTestSubject('advancedSetting-' + propertyName + '-currentValue') .getVisibleText(); @@ -173,7 +173,7 @@ export default class SettingsPage { }); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Bluebird.all(getChartTypesPromises); }); } @@ -188,8 +188,8 @@ export default class SettingsPage { } getFieldsTabCount() { - var self = this; - var selector = 'li.kbn-management-tab.active a small'; + let self = this; + let selector = 'li.kbn-management-tab.active a small'; return PageObjects.common.try(function () { return self.remote.setFindTimeout(defaultFindTimeout / 10) @@ -202,12 +202,12 @@ export default class SettingsPage { } getPageSize() { - var selectedItemLabel = ''; + let selectedItemLabel = ''; return this.remote.setFindTimeout(defaultFindTimeout) .findAllByCssSelector('select.ng-pristine.ng-valid.ng-untouched option') .then(function (chartTypes) { function getChartType(chart) { - var thisChart = chart; + let thisChart = chart; return chart.isSelected() .then(function (isSelected) { if (isSelected === true) { @@ -219,7 +219,7 @@ export default class SettingsPage { }); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Bluebird.all(getChartTypesPromises); }) .then(() => { @@ -334,7 +334,7 @@ export default class SettingsPage { } removeIndexPattern() { - var alertText; + let alertText; return PageObjects.common.try(() => { PageObjects.common.debug('click delete index pattern button'); diff --git a/test/support/page_objects/shield_page.js b/test/support/page_objects/shield_page.js index 5840169cdba02..529ef9c59ade0 100644 --- a/test/support/page_objects/shield_page.js +++ b/test/support/page_objects/shield_page.js @@ -10,7 +10,7 @@ export default class ShieldPage { } login(user, pwd) { - var remote = this.remote; + let remote = this.remote; return remote.setFindTimeout(defaultFindTimeout) .findById('username') .type(user) diff --git a/test/support/page_objects/visualize_page.js b/test/support/page_objects/visualize_page.js index e92288c0232e4..caa40f639c590 100644 --- a/test/support/page_objects/visualize_page.js +++ b/test/support/page_objects/visualize_page.js @@ -83,7 +83,7 @@ export default class VisualizePage { function getChartType(chart) { return chart.getVisibleText(); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }) .then(function (texts) { @@ -208,7 +208,7 @@ export default class VisualizePage { } }); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }); } @@ -228,7 +228,7 @@ export default class VisualizePage { } selectField(fieldValue) { - var self = this; + let self = this; return PageObjects.common.try(function tryingForTime() { return self.remote .setFindTimeout(defaultFindTimeout) @@ -356,7 +356,7 @@ export default class VisualizePage { } clickVisualizationByLinkText(vizName) { - var self = this; + let self = this; PageObjects.common.debug('clickVisualizationByLinkText(' + vizName + ')'); return PageObjects.common.try(function tryingForTime() { @@ -370,7 +370,7 @@ export default class VisualizePage { // this starts by clicking the Load Saved Viz button, not from the // bottom half of the "Create a new visualization Step 1" page loadSavedVisualization(vizName) { - var self = this; + let self = this; return this.clickLoadSavedVisButton() .then(function filterVisualization() { return self.openSavedVisualization(vizName); @@ -380,7 +380,7 @@ export default class VisualizePage { // this is for starting on the // bottom half of the "Create a new visualization Step 1" page openSavedVisualization(vizName) { - var self = this; + let self = this; return self.filterVisByName(vizName) .then(() => { return PageObjects.common.sleep(1000); @@ -399,7 +399,7 @@ export default class VisualizePage { return chart .getVisibleText(); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }) .then(texts => { @@ -418,7 +418,7 @@ export default class VisualizePage { return chart .getVisibleText(); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }) .then(texts => { @@ -434,13 +434,13 @@ export default class VisualizePage { */ getAreaChartData(aggregateName) { - var self = this.remote; - var chartData = []; - var tempArray = []; - var chartSections = 0; - var height = 0; - var yAxisLabel = 0; - var yAxisHeight = 0; + let self = this.remote; + let chartData = []; + let tempArray = []; + let chartSections = 0; + let height = 0; + let yAxisLabel = 0; + let yAxisHeight = 0; // 1). get the maximim chart Y-Axis marker value return this.remote @@ -479,7 +479,7 @@ export default class VisualizePage { tempArray = data.replace('M','').split('L'); chartSections = tempArray.length / 2; PageObjects.common.debug('chartSections = ' + chartSections + ' height = ' + yAxisHeight + ' yAxisLabel = ' + yAxisLabel); - for (var i = 0; i < chartSections; i++) { + for (let i = 0; i < chartSections; i++) { chartData[i] = Math.round((yAxisHeight - tempArray[i].split(',')[1]) / yAxisHeight * yAxisLabel); PageObjects.common.debug('chartData[i] =' + chartData[i]); } @@ -490,9 +490,9 @@ export default class VisualizePage { // The current test shows dots, not a line. This function gets the dots and normalizes their height. getLineChartData(cssPart) { - var self = this.remote; - var yAxisLabel = 0; - var yAxisHeight; + let self = this.remote; + let yAxisLabel = 0; + let yAxisHeight; // 1). get the maximim chart Y-Axis marker value return this.remote @@ -540,7 +540,7 @@ export default class VisualizePage { } // 4). pass the chartTypes to the getChartType function - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }); }) @@ -553,9 +553,9 @@ export default class VisualizePage { // this is ALMOST identical to DiscoverPage.getBarChartData getBarChartData() { - var self = this.remote; - var yAxisLabel = 0; - var yAxisHeight; + let self = this.remote; + let yAxisLabel = 0; + let yAxisHeight; // 1). get the maximim chart Y-Axis marker value return this.remote @@ -606,7 +606,7 @@ export default class VisualizePage { } }); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }) .then(function (bars) { @@ -629,7 +629,7 @@ export default class VisualizePage { return slice; }); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }) .then(function (slices) { @@ -673,7 +673,7 @@ export default class VisualizePage { } waitForToastMessageGone() { - var self = this; + let self = this; return PageObjects.common.try(function tryingForTime() { return self.remote .setFindTimeout(100) @@ -745,8 +745,8 @@ export default class VisualizePage { .then((chartTypes) => { function getChartType(chart) { - var color; - var radius; + let color; + let radius; return chart.getAttribute('stroke') .then((stroke) => { color = stroke; @@ -763,7 +763,7 @@ export default class VisualizePage { return {color: color, radius: radius}; }); } - var getChartTypesPromises = chartTypes.map(getChartType); + let getChartTypesPromises = chartTypes.map(getChartType); return Promise.all(getChartTypesPromises); }) .then((circles) => { diff --git a/test/support/utils/elastic_dump.js b/test/support/utils/elastic_dump.js index e019a4497e717..cb1f167523547 100644 --- a/test/support/utils/elastic_dump.js +++ b/test/support/utils/elastic_dump.js @@ -4,11 +4,11 @@ import { } from './'; export default (function () { - var util = require('util'); - var path = require('path'); - var url = require('url'); - var resolve = require('path').resolve; - var Elasticdump = require('elasticdump').elasticdump; + let util = require('util'); + let path = require('path'); + let url = require('url'); + let resolve = require('path').resolve; + let Elasticdump = require('elasticdump').elasticdump; function ElasticDump() { } @@ -22,7 +22,7 @@ export default (function () { */ elasticdumpModule: function elasticdumpModule(myinput, myoutput, index, mytype) { - var options = { + let options = { limit: 100, offset: 0, debug: false, @@ -46,12 +46,12 @@ export default (function () { skip: null, toLog: null, }; - var dumper = new Elasticdump(options.input, options.output, options); + let dumper = new Elasticdump(options.input, options.output, options); dumper.on('log', function (message) { Log.debug(message); }); dumper.on('error', function (error) { Log.debug('error', 'Error Emitted => ' + (error.message || JSON.stringify(error))); }); - var promise = new Promise(function (resolve, reject) { + let promise = new Promise(function (resolve, reject) { dumper.dump(function (error, totalWrites) { if (error) { Log.debug('THERE WAS AN ERROR :-('); @@ -72,7 +72,7 @@ export default (function () { ** Fails if the files already exist, so consider appending a timestamp to filename. */ elasticDump: function elasticDump(index, file) { - var self = this; + let self = this; Log.debug('Dumping mapping from ' + url.format(config.servers.elasticsearch) + '/' + index + ' to (' + file + '.mapping.json)'); return this.elasticdumpModule(url.format(config.servers.elasticsearch), @@ -94,7 +94,7 @@ export default (function () { elasticLoad: function elasticLoad(file, index) { // TODO: should we have a flag to delete the index first? // or use scenarioManager.unload(index) ? <<- currently this - var self = this; + let self = this; Log.debug('Loading mapping (test/fixtures/dump_data/' + file + '.mapping.json) into ' + url.format(config.servers.elasticsearch) + '/' + index); return this.elasticdumpModule('test/fixtures/dump_data/' + file + '.mapping.json', diff --git a/test/support/utils/es_client.js b/test/support/utils/es_client.js index 1edbaefe0a27d..5d0394d240d9c 100644 --- a/test/support/utils/es_client.js +++ b/test/support/utils/es_client.js @@ -6,8 +6,8 @@ import { export default (function () { - var elasticsearch = require('elasticsearch'); - var Promise = require('bluebird'); + let elasticsearch = require('elasticsearch'); + let Promise = require('bluebird'); function EsClient(server) { if (!server) throw new Error('No server defined'); @@ -50,7 +50,7 @@ export default (function () { ** Also used after deleting .kibana index to know Kibana has recreated it. */ getConfigId: function () { - var configId; + let configId; return this.client.search({ index: '.kibana', @@ -78,7 +78,7 @@ export default (function () { ** Gets defaultIndex from the config doc. */ getDefaultIndex: function () { - var defaultIndex; + let defaultIndex; return this.client.search({ index: '.kibana', @@ -108,9 +108,9 @@ export default (function () { */ updateConfigDoc: function (docMap) { // first we need to get the config doc's id so we can use it in our _update call - var self = this; - var configId; - var docMapString = JSON.stringify(docMap); + let self = this; + let configId; + let docMapString = JSON.stringify(docMap); return this.getConfigId() // now that we have the id, we can update @@ -137,8 +137,8 @@ export default (function () { * @return {Promise} A promise that is resolved when elasticsearch has a response */ deleteAndUpdateConfigDoc: function (docMap) { - var self = this; - var configId; + let self = this; + let configId; return this.delete('.kibana') .then(function () { @@ -147,7 +147,7 @@ export default (function () { return self.getConfigId(); }); } else { - var docMapString = JSON.stringify(docMap); + let docMapString = JSON.stringify(docMap); return Try.try(function () { return self.updateConfigDoc(docMap); }); diff --git a/test/support/utils/try.js b/test/support/utils/try.js index 6eb0b58912abb..876c64184cc46 100644 --- a/test/support/utils/try.js +++ b/test/support/utils/try.js @@ -10,12 +10,12 @@ import Log from './log.js'; class Try { tryForTime(timeout, block) { - var self = this; - var start = Date.now(); - var retryDelay = 502; - var lastTry = 0; - var finalMessage; - var prevMessage; + let self = this; + let start = Date.now(); + let retryDelay = 502; + let lastTry = 0; + let finalMessage; + let prevMessage; function attempt() { lastTry = Date.now(); diff --git a/test/unit/api/ingest/_field_capabilities.js b/test/unit/api/ingest/_field_capabilities.js index e4f8b0f3eb62f..ed46d6ba44c71 100644 --- a/test/unit/api/ingest/_field_capabilities.js +++ b/test/unit/api/ingest/_field_capabilities.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); export default function (bdd, scenarioManager, request) { bdd.describe('field_capabilities API', function postIngest() { @@ -44,7 +44,7 @@ export default function (bdd, scenarioManager, request) { return request.get('/kibana/foo-1/field_capabilities') .expect(200) .then(function (response) { - var fields = response.body.fields; + let fields = response.body.fields; expect(fields.foo).to.eql({searchable: true, aggregatable: false}); expect(fields['foo.keyword']).to.eql({searchable: true, aggregatable: true}); expect(fields).to.not.have.property('baz'); @@ -55,7 +55,7 @@ export default function (bdd, scenarioManager, request) { return request.get('/kibana/foo-*/field_capabilities') .expect(200) .then(function (response) { - var fields = response.body.fields; + let fields = response.body.fields; expect(fields.foo).to.eql({searchable: true, aggregatable: false}); expect(fields.baz).to.eql({searchable: true, aggregatable: false}); }); @@ -65,7 +65,7 @@ export default function (bdd, scenarioManager, request) { return request.get('/kibana/foo-1,foo-2/field_capabilities') .expect(200) .then(function (response) { - var fields = response.body.fields; + let fields = response.body.fields; expect(fields.foo).to.eql({searchable: true, aggregatable: false}); expect(fields.baz).to.eql({searchable: true, aggregatable: false}); }); diff --git a/test/unit/api/ingest/_processors.js b/test/unit/api/ingest/_processors.js index 1fb94d2c2ac0f..b5711f2ea57e3 100644 --- a/test/unit/api/ingest/_processors.js +++ b/test/unit/api/ingest/_processors.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); export default function (bdd, scenarioManager, request) { bdd.describe('processors', () => { diff --git a/test/unit/api/ingest/_simulate.js b/test/unit/api/ingest/_simulate.js index 4110a5f4dd70a..56154fdf6b09b 100644 --- a/test/unit/api/ingest/_simulate.js +++ b/test/unit/api/ingest/_simulate.js @@ -1,7 +1,7 @@ -var Promise = require('bluebird'); -var createTestData = require('intern/dojo/node!../../../unit/api/ingest/data'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let createTestData = require('intern/dojo/node!../../../unit/api/ingest/data'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/index.js b/test/unit/api/ingest/index.js index ab4356c8328b8..b94b6608f728d 100644 --- a/test/unit/api/ingest/index.js +++ b/test/unit/api/ingest/index.js @@ -1,17 +1,17 @@ -var bdd = require('intern!bdd'); -var serverConfig = require('intern/dojo/node!../../../server_config'); -var ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); -var request = require('intern/dojo/node!supertest-as-promised'); -var url = require('intern/dojo/node!url'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); -var simulate = require('./_simulate'); -var processors = require('./_processors'); -var processorTypes = require('./processors/index'); -var fieldCapabilities = require('./_field_capabilities'); +let bdd = require('intern!bdd'); +let serverConfig = require('intern/dojo/node!../../../server_config'); +let ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); +let request = require('intern/dojo/node!supertest-as-promised'); +let url = require('intern/dojo/node!url'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); +let simulate = require('./_simulate'); +let processors = require('./_processors'); +let processorTypes = require('./processors/index'); +let fieldCapabilities = require('./_field_capabilities'); bdd.describe('ingest API', function () { - var scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); + let scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); request = request(url.format(serverConfig.servers.kibana) + '/api'); bdd.before(function () { diff --git a/test/unit/api/ingest/processors/_append.js b/test/unit/api/ingest/processors/_append.js index b82591e684409..5195874576747 100644 --- a/test/unit/api/ingest/processors/_append.js +++ b/test/unit/api/ingest/processors/_append.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_convert.js b/test/unit/api/ingest/processors/_convert.js index a186d3e0aef27..36254333e09ed 100644 --- a/test/unit/api/ingest/processors/_convert.js +++ b/test/unit/api/ingest/processors/_convert.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_date.js b/test/unit/api/ingest/processors/_date.js index b011ec8c49dea..4ed37a293f542 100644 --- a/test/unit/api/ingest/processors/_date.js +++ b/test/unit/api/ingest/processors/_date.js @@ -1,7 +1,7 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); -var moment = require('intern/dojo/node!moment'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); +let moment = require('intern/dojo/node!moment'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_geoip.js b/test/unit/api/ingest/processors/_geoip.js index 4a610af00597d..ecf7a95b87c5e 100644 --- a/test/unit/api/ingest/processors/_geoip.js +++ b/test/unit/api/ingest/processors/_geoip.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_grok.js b/test/unit/api/ingest/processors/_grok.js index 7604b37785236..7f9b7c5411ca6 100644 --- a/test/unit/api/ingest/processors/_grok.js +++ b/test/unit/api/ingest/processors/_grok.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_gsub.js b/test/unit/api/ingest/processors/_gsub.js index 8038fba513d84..1a3b2f4357a6a 100644 --- a/test/unit/api/ingest/processors/_gsub.js +++ b/test/unit/api/ingest/processors/_gsub.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_join.js b/test/unit/api/ingest/processors/_join.js index c82353c8bbbd2..aaff1e2f51e28 100644 --- a/test/unit/api/ingest/processors/_join.js +++ b/test/unit/api/ingest/processors/_join.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_lowercase.js b/test/unit/api/ingest/processors/_lowercase.js index c3809d03746f7..13a52bfcd9c69 100644 --- a/test/unit/api/ingest/processors/_lowercase.js +++ b/test/unit/api/ingest/processors/_lowercase.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_remove.js b/test/unit/api/ingest/processors/_remove.js index fa37e13f9e2ca..75582b3e3d5b1 100644 --- a/test/unit/api/ingest/processors/_remove.js +++ b/test/unit/api/ingest/processors/_remove.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_rename.js b/test/unit/api/ingest/processors/_rename.js index 145021411a770..aed12a2cd05c6 100644 --- a/test/unit/api/ingest/processors/_rename.js +++ b/test/unit/api/ingest/processors/_rename.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_set.js b/test/unit/api/ingest/processors/_set.js index 0894bdbbfc3ae..0fb74e7b6edca 100644 --- a/test/unit/api/ingest/processors/_set.js +++ b/test/unit/api/ingest/processors/_set.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_split.js b/test/unit/api/ingest/processors/_split.js index 98b1c112cc9a6..56270968aae9f 100644 --- a/test/unit/api/ingest/processors/_split.js +++ b/test/unit/api/ingest/processors/_split.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_trim.js b/test/unit/api/ingest/processors/_trim.js index 817233f1a2022..11edfacd6edbd 100644 --- a/test/unit/api/ingest/processors/_trim.js +++ b/test/unit/api/ingest/processors/_trim.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/_uppercase.js b/test/unit/api/ingest/processors/_uppercase.js index de0f4091015de..68b7c6d47e118 100644 --- a/test/unit/api/ingest/processors/_uppercase.js +++ b/test/unit/api/ingest/processors/_uppercase.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); const testPipeline = { processors: [{ diff --git a/test/unit/api/ingest/processors/index.js b/test/unit/api/ingest/processors/index.js index 9c0df6658d2fb..fa6a31c0dc554 100644 --- a/test/unit/api/ingest/processors/index.js +++ b/test/unit/api/ingest/processors/index.js @@ -1,17 +1,17 @@ -var append = require('./_append'); -var convert = require('./_convert'); -var date = require('./_date'); -var geoip = require('./_geoip'); -var grok = require('./_grok'); -var gsub = require('./_gsub'); -var join = require('./_join'); -var lowercase = require('./_lowercase'); -var remove = require('./_remove'); -var rename = require('./_rename'); -var set = require('./_set'); -var split = require('./_split'); -var trim = require('./_trim'); -var uppercase = require('./_uppercase'); +let append = require('./_append'); +let convert = require('./_convert'); +let date = require('./_date'); +let geoip = require('./_geoip'); +let grok = require('./_grok'); +let gsub = require('./_gsub'); +let join = require('./_join'); +let lowercase = require('./_lowercase'); +let remove = require('./_remove'); +let rename = require('./_rename'); +let set = require('./_set'); +let split = require('./_split'); +let trim = require('./_trim'); +let uppercase = require('./_uppercase'); export default function processors(bdd, scenarioManager, request) { append(bdd, scenarioManager, request); diff --git a/test/unit/api/scripts/_languages.js b/test/unit/api/scripts/_languages.js index 837775e424ce2..fb831f21c29ef 100644 --- a/test/unit/api/scripts/_languages.js +++ b/test/unit/api/scripts/_languages.js @@ -1,4 +1,4 @@ -var expect = require('intern/dojo/node!expect.js'); +let expect = require('intern/dojo/node!expect.js'); export default function (bdd, request) { bdd.describe('Languages API', function getLanguages() { diff --git a/test/unit/api/scripts/index.js b/test/unit/api/scripts/index.js index 5963e4efdb1db..ac488118050c3 100644 --- a/test/unit/api/scripts/index.js +++ b/test/unit/api/scripts/index.js @@ -1,8 +1,8 @@ -var bdd = require('intern!bdd'); -var serverConfig = require('intern/dojo/node!../../../server_config'); -var request = require('intern/dojo/node!supertest-as-promised'); -var url = require('intern/dojo/node!url'); -var languages = require('./_languages'); +let bdd = require('intern!bdd'); +let serverConfig = require('intern/dojo/node!../../../server_config'); +let request = require('intern/dojo/node!supertest-as-promised'); +let url = require('intern/dojo/node!url'); +let languages = require('./_languages'); bdd.describe('scripts API', function () { request = request(url.format(serverConfig.servers.kibana) + '/api'); diff --git a/test/unit/api/search/_count.js b/test/unit/api/search/_count.js index 52e7debe1594a..343e311a979aa 100644 --- a/test/unit/api/search/_count.js +++ b/test/unit/api/search/_count.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'); -var _ = require('intern/dojo/node!lodash'); -var expect = require('intern/dojo/node!expect.js'); +let Promise = require('bluebird'); +let _ = require('intern/dojo/node!lodash'); +let expect = require('intern/dojo/node!expect.js'); export default function (bdd, scenarioManager, request) { bdd.describe('Count API', function postIngest() { diff --git a/test/unit/api/search/index.js b/test/unit/api/search/index.js index 7e430e01dbd9c..615cdf63e5c71 100644 --- a/test/unit/api/search/index.js +++ b/test/unit/api/search/index.js @@ -1,12 +1,12 @@ -var bdd = require('intern!bdd'); -var serverConfig = require('intern/dojo/node!../../../server_config'); -var ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); -var request = require('intern/dojo/node!supertest-as-promised'); -var url = require('intern/dojo/node!url'); -var count = require('./_count'); +let bdd = require('intern!bdd'); +let serverConfig = require('intern/dojo/node!../../../server_config'); +let ScenarioManager = require('intern/dojo/node!../../../fixtures/scenario_manager'); +let request = require('intern/dojo/node!supertest-as-promised'); +let url = require('intern/dojo/node!url'); +let count = require('./_count'); bdd.describe('search API', function () { - var scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); + let scenarioManager = new ScenarioManager(url.format(serverConfig.servers.elasticsearch)); request = request(url.format(serverConfig.servers.kibana) + '/api'); bdd.before(function () { diff --git a/test/utils/__tests__/get_page.js b/test/utils/__tests__/get_page.js index d46f23c77359e..ac61ad2760ff3 100644 --- a/test/utils/__tests__/get_page.js +++ b/test/utils/__tests__/get_page.js @@ -1,9 +1,9 @@ -var expect = require('expect.js'); -var getUrl = require('../get_url'); +let expect = require('expect.js'); +let getUrl = require('../get_url'); describe('getUrl', function () { it('should convert to a url', function () { - var url = getUrl({ + let url = getUrl({ protocol: 'http', hostname: 'localhost', }, { @@ -14,7 +14,7 @@ describe('getUrl', function () { }); it('should convert to a url with port', function () { - var url = getUrl({ + let url = getUrl({ protocol: 'http', hostname: 'localhost', port: 9220 diff --git a/test/utils/get_url.js b/test/utils/get_url.js index 8dd676d98b627..cff9f6c5cb6a1 100644 --- a/test/utils/get_url.js +++ b/test/utils/get_url.js @@ -1,5 +1,5 @@ -var _ = require('lodash'); -var url = require('url'); +let _ = require('lodash'); +let url = require('url'); /** * Converts a config and a pathname to a url diff --git a/test/visual_regression/home/_loading.js b/test/visual_regression/home/_loading.js index a3d77860f34f8..97aa0b81088ff 100644 --- a/test/visual_regression/home/_loading.js +++ b/test/visual_regression/home/_loading.js @@ -5,7 +5,7 @@ import { consolePage } from '../../support'; -var expect = require('expect.js'); +let expect = require('expect.js'); bdd.describe('Loading', function coverLoadingUi() { bdd.it('should show loading feebdack', async function () { From 82d2f3b1e35a81d47583438b96e162db2218cebb Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 4 Nov 2016 12:57:17 -0700 Subject: [PATCH 11/33] re-enable prefer-const rule --- .eslintrc | 1 - 1 file changed, 1 deletion(-) diff --git a/.eslintrc b/.eslintrc index 76c42539c061c..90770468d6db1 100644 --- a/.eslintrc +++ b/.eslintrc @@ -2,6 +2,5 @@ extends: '@elastic/kibana' rules: no-unused-vars: off - prefer-const: off no-extra-semi: off quotes: off From 24968364dd3a13da8ef3608a78ed0a70fa7f803f Mon Sep 17 00:00:00 2001 From: spalger Date: Fri, 4 Nov 2016 12:58:43 -0700 Subject: [PATCH 12/33] `eslint --fix` with prefer-const enabled --- src/cli/cluster/worker.js | 14 +- src/cli/command.js | 12 +- src/cli/help.js | 18 +- src/cli/log.js | 2 +- src/cli_plugin/cli.js | 8 +- src/cli_plugin/install/__tests__/index.js | 2 +- src/cli_plugin/install/downloaders/file.js | 2 +- src/cli_plugin/install/downloaders/http.js | 2 +- .../lib/__tests__/is_upgradeable.js | 6 +- .../kbn_doc_views/public/views/table.js | 2 +- src/core_plugins/kibana/index.js | 2 +- .../dashboard/__tests__/dashboard_panels.js | 6 +- .../directives/output_preview.js | 4 +- .../pipeline_setup/lib/__tests__/keys_deep.js | 16 +- .../pipeline_setup/lib/keys_deep.js | 4 +- .../kibana/public/visualize/editor/editor.js | 2 +- .../create_mappings_from_pattern_fields.js | 8 +- .../table_vis/public/table_vis_controller.js | 2 +- .../tests_bundle/find_source_files.js | 2 +- src/core_plugins/tests_bundle/index.js | 8 +- src/core_plugins/timelion/index.js | 10 +- src/core_plugins/timelion/init.js | 6 +- src/core_plugins/timelion/public/app.js | 26 +-- .../timelion/public/directives/cells/cells.js | 8 +- .../timelion/public/directives/chart/chart.js | 6 +- .../timelion/public/directives/docs.js | 10 +- .../public/directives/expression_directive.js | 36 ++-- .../public/directives/fixed_element.js | 12 +- .../directives/fullscreen/fullscreen.js | 8 +- .../public/directives/interval/interval.js | 10 +- .../public/directives/refresh_hack.js | 6 +- .../public/directives/timelion_grid.js | 12 +- .../public/panels/timechart/schema.js | 54 ++--- .../public/panels/timechart/timechart.js | 4 +- .../panels/timechart/xaxis_formatter.js | 10 +- .../public/services/dashboard_context.js | 12 +- .../timelion/public/services/saved_sheets.js | 8 +- src/core_plugins/timelion/public/vis/index.js | 2 +- .../public/vis/timelion_vis_controller.js | 16 +- .../vis/timelion_vis_params_controller.js | 2 +- .../server/fit_functions/__test__/average.js | 22 +- .../server/fit_functions/__test__/carry.js | 22 +- .../timelion/server/fit_functions/average.js | 20 +- .../timelion/server/fit_functions/carry.js | 8 +- .../timelion/server/fit_functions/nearest.js | 8 +- .../timelion/server/fit_functions/scale.js | 4 +- .../timelion/server/handlers/chain_runner.js | 50 ++--- .../timelion/server/handlers/lib/arg_type.js | 2 +- .../server/handlers/lib/index_arguments.js | 14 +- .../server/handlers/lib/parse_sheet.js | 12 +- .../server/handlers/lib/preprocess_chain.js | 4 +- .../handlers/lib/reposition_arguments.js | 6 +- .../timelion/server/handlers/lib/tl_config.js | 4 +- .../server/handlers/lib/validate_arg.js | 12 +- .../server/handlers/lib/validate_time.js | 12 +- .../server/lib/__test__/load_functions.js | 12 +- src/core_plugins/timelion/server/lib/alter.js | 8 +- .../timelion/server/lib/asSorted.js | 6 +- .../timelion/server/lib/build_target.js | 12 +- .../timelion/server/lib/classes/chainable.js | 2 +- .../timelion/server/lib/classes/datasource.js | 16 +- .../server/lib/classes/timelion_function.js | 12 +- .../timelion/server/lib/date_math.js | 12 +- .../timelion/server/lib/functions_md.js | 10 +- .../server/lib/get_namespaced_settings.js | 10 +- .../timelion/server/lib/load_functions.js | 22 +- .../timelion/server/lib/offset_time.js | 8 +- .../server/lib/process_function_definition.js | 6 +- .../timelion/server/lib/reduce.js | 8 +- .../timelion/server/lib/split_interval.js | 2 +- .../timelion/server/lib/to_milliseconds.js | 14 +- .../timelion/server/lib/unzipPairs.js | 4 +- .../timelion/server/routes/functions.js | 4 +- .../timelion/server/routes/run.js | 16 +- .../timelion/server/routes/validate_es.js | 6 +- .../server/series_functions/__tests__/abs.js | 16 +- .../server/series_functions/__tests__/bars.js | 16 +- .../series_functions/__tests__/condition.js | 14 +- .../server/series_functions/__tests__/es.js | 8 +- .../series_functions/__tests__/first.js | 10 +- .../server/series_functions/__tests__/fit.js | 24 +-- .../__tests__/fixtures/bucketList.js | 2 +- .../__tests__/fixtures/seriesList.js | 10 +- .../__tests__/fixtures/tlConfig.js | 6 +- .../series_functions/__tests__/graphite.js | 16 +- .../__tests__/helpers/get_series.js | 4 +- .../__tests__/helpers/get_series_list.js | 2 +- .../helpers/get_single_series_list.js | 6 +- .../__tests__/helpers/invoke_series_fn.js | 10 +- .../series_functions/__tests__/movingstd.js | 2 +- .../series_functions/__tests__/points.js | 2 +- .../series_functions/__tests__/quandl.js | 18 +- .../timelion/server/series_functions/abs.js | 8 +- .../timelion/server/series_functions/bars.js | 4 +- .../timelion/server/series_functions/color.js | 6 +- .../server/series_functions/condition.js | 20 +- .../timelion/server/series_functions/cusum.js | 8 +- .../server/series_functions/derivative.js | 8 +- .../server/series_functions/divide.js | 4 +- .../server/series_functions/es/index.js | 16 +- .../es/lib/agg_response_to_series_list.js | 8 +- .../series_functions/es/lib/build_request.js | 10 +- .../es/lib/create_date_agg.js | 6 +- .../timelion/server/series_functions/first.js | 4 +- .../timelion/server/series_functions/fit.js | 12 +- .../server/series_functions/graphite.js | 18 +- .../timelion/server/series_functions/hide.js | 4 +- .../server/series_functions/holt/index.js | 16 +- .../server/series_functions/holt/lib/des.js | 4 +- .../server/series_functions/holt/lib/ses.js | 2 +- .../server/series_functions/holt/lib/tes.js | 14 +- .../timelion/server/series_functions/label.js | 8 +- .../server/series_functions/legend.js | 4 +- .../timelion/server/series_functions/lines.js | 4 +- .../timelion/server/series_functions/log.js | 10 +- .../timelion/server/series_functions/max.js | 4 +- .../timelion/server/series_functions/min.js | 4 +- .../server/series_functions/movingaverage.js | 18 +- .../server/series_functions/movingstd.js | 12 +- .../server/series_functions/multiply.js | 4 +- .../server/series_functions/points.js | 8 +- .../server/series_functions/precision.js | 6 +- .../timelion/server/series_functions/props.js | 12 +- .../server/series_functions/quandl.js | 18 +- .../timelion/server/series_functions/range.js | 16 +- .../server/series_functions/scale_interval.js | 14 +- .../server/series_functions/static.js | 20 +- .../server/series_functions/subtract.js | 4 +- .../timelion/server/series_functions/sum.js | 4 +- .../timelion/server/series_functions/title.js | 4 +- .../server/series_functions/trend/index.js | 8 +- .../series_functions/trend/lib/regress.js | 30 +-- .../timelion/server/series_functions/trim.js | 10 +- .../server/series_functions/worldbank.js | 20 +- .../series_functions/worldbank_indicators.js | 22 +- .../timelion/server/series_functions/yaxis.js | 6 +- src/fixtures/agg_resp/geohash_grid.js | 8 +- src/fixtures/fake_chart_events.js | 2 +- src/fixtures/fake_hierarchical_data.js | 2 +- src/fixtures/fake_row.js | 2 +- src/fixtures/mock_courier.js | 6 +- src/fixtures/mock_ui_state.js | 2 +- src/fixtures/stubbed_doc_source_response.js | 2 +- .../stubbed_logstash_index_pattern.js | 12 +- src/fixtures/stubbed_search_source.js | 2 +- src/fixtures/vislib/_vis_fixture.js | 6 +- src/optimize/babel_options.build.js | 2 +- src/optimize/babel_options.js | 4 +- src/optimize/base_optimizer.js | 16 +- src/optimize/fs_optimizer.js | 2 +- src/optimize/index.js | 12 +- src/optimize/lazy/lazy_optimizer.js | 6 +- src/optimize/lazy/optmzr_role.js | 4 +- src/optimize/lazy/proxy_role.js | 4 +- src/optimize/lazy/weird_control_flow.js | 2 +- src/server/config/__tests__/config.js | 50 ++--- src/server/config/__tests__/explode_by.js | 4 +- src/server/config/__tests__/flatten_with.js | 2 +- src/server/config/__tests__/override.js | 4 +- src/server/config/complete.js | 2 +- src/server/config/config.js | 14 +- src/server/config/explode_by.js | 6 +- src/server/config/flatten_with.js | 4 +- src/server/config/override.js | 4 +- src/server/http/index.js | 4 +- src/server/kbn_server.js | 4 +- .../__tests__/apply_filters_to_keys.js | 2 +- src/server/logging/apply_filters_to_keys.js | 6 +- src/server/logging/configuration.js | 2 +- src/server/logging/log_format.js | 8 +- src/server/logging/log_format_json.js | 2 +- src/server/logging/log_format_string.js | 16 +- src/server/pid/index.js | 10 +- src/server/plugins/check_enabled.js | 2 +- src/server/plugins/check_version.js | 4 +- src/server/plugins/initialize.js | 2 +- src/server/plugins/plugin.js | 4 +- src/server/plugins/plugin_collection.js | 16 +- src/server/plugins/plugin_init.js | 10 +- src/server/plugins/scan.js | 16 +- src/server/status/__tests__/server_status.js | 20 +- src/server/status/__tests__/status.js | 30 +-- src/server/status/metrics.js | 10 +- src/server/status/samples.js | 4 +- src/server/status/server_status.js | 10 +- src/server/status/status.js | 4 +- src/test_utils/simulate_keys.js | 14 +- src/test_utils/stub_index_pattern.js | 6 +- src/ui/__tests__/ui_exports.js | 4 +- src/ui/index.js | 6 +- .../geo_json/__tests__/geo_json.js | 32 +-- .../geo_json/_tooltip_formatter.js | 14 +- .../public/agg_response/geo_json/geo_json.js | 14 +- .../agg_response/geo_json/rows_to_features.js | 8 +- .../__tests__/build_hierarchical_data.js | 14 +- .../hierarchical/__tests__/collect_branch.js | 2 +- .../hierarchical/__tests__/create_raw_data.js | 4 +- .../hierarchical/__tests__/extract_buckets.js | 10 +- .../__tests__/transform_aggregation.js | 8 +- .../agg_response/hierarchical/_build_split.js | 4 +- .../hierarchical/_collect_branch.js | 4 +- .../hierarchical/_collect_keys.js | 4 +- .../hierarchical/_create_raw_data.js | 14 +- .../hierarchical/_extract_buckets.js | 2 +- .../_hierarchical_tooltip_formatter.js | 8 +- .../hierarchical/_transform_aggregation.js | 6 +- .../hierarchical/build_hierarchical_data.js | 32 +-- .../point_series/__tests__/_add_to_siri.js | 22 +- .../point_series/__tests__/_fake_x_aspect.js | 4 +- .../point_series/__tests__/_get_aspects.js | 12 +- .../point_series/__tests__/_get_point.js | 26 +-- .../point_series/__tests__/_get_series.js | 36 ++-- .../point_series/__tests__/_init_x_axis.js | 8 +- .../point_series/__tests__/_init_y_axis.js | 12 +- .../point_series/__tests__/_main.js | 84 ++++---- .../__tests__/_ordered_date_axis.js | 18 +- .../__tests__/_tooltip_formatter.js | 14 +- .../point_series/_fake_x_aspect.js | 8 +- .../agg_response/point_series/_get_aspects.js | 12 +- .../agg_response/point_series/_get_point.js | 6 +- .../agg_response/point_series/_get_series.js | 20 +- .../agg_response/point_series/_init_x_axis.js | 4 +- .../agg_response/point_series/_init_y_axis.js | 6 +- .../point_series/_ordered_date_axis.js | 10 +- .../point_series/_tooltip_formatter.js | 14 +- .../agg_response/point_series/point_series.js | 18 +- .../agg_response/tabify/__tests__/_buckets.js | 18 +- .../tabify/__tests__/_get_columns.js | 22 +- .../tabify/__tests__/_integration.js | 14 +- .../tabify/__tests__/_response_writer.js | 126 +++++------ .../agg_response/tabify/__tests__/_table.js | 26 +-- .../tabify/__tests__/_table_group.js | 2 +- src/ui/public/agg_response/tabify/_buckets.js | 2 +- .../agg_response/tabify/_get_columns.js | 8 +- .../agg_response/tabify/_response_writer.js | 44 ++-- src/ui/public/agg_response/tabify/tabify.js | 22 +- src/ui/public/agg_table/__tests__/_group.js | 18 +- src/ui/public/agg_table/__tests__/_table.js | 42 ++-- src/ui/public/agg_table/agg_table.js | 24 +-- src/ui/public/agg_table/agg_table_group.js | 6 +- .../agg_types/__tests__/agg_param_writer.js | 16 +- .../public/agg_types/__tests__/agg_params.js | 20 +- src/ui/public/agg_types/__tests__/agg_type.js | 30 +-- .../__tests__/bucket_count_between.js | 56 ++--- .../agg_types/__tests__/buckets/_geo_hash.js | 2 +- .../agg_types/__tests__/buckets/_histogram.js | 22 +- .../agg_types/__tests__/buckets/_range.js | 10 +- .../buckets/create_filter/date_histogram.js | 16 +- .../buckets/create_filter/date_range.js | 6 +- .../buckets/create_filter/filters.js | 6 +- .../buckets/create_filter/histogram.js | 6 +- .../buckets/create_filter/ip_range.js | 12 +- .../__tests__/buckets/create_filter/range.js | 6 +- .../__tests__/buckets/create_filter/terms.js | 6 +- .../buckets/date_histogram/_editor.js | 14 +- .../buckets/date_histogram/_params.js | 42 ++-- .../__tests__/controls/number_list.js | 14 +- .../agg_types/__tests__/metrics/median.js | 4 +- .../__tests__/metrics/std_deviation.js | 20 +- .../param_types/_calculate_interval.js | 10 +- .../agg_types/__tests__/param_types/_field.js | 2 +- .../__tests__/param_types/_optioned.js | 2 +- .../__tests__/param_types/_raw_json.js | 10 +- .../agg_types/__tests__/param_types/_regex.js | 8 +- .../__tests__/param_types/_string.js | 12 +- .../__tests__/utils/_stub_agg_params.js | 4 +- src/ui/public/agg_types/agg_params.js | 8 +- src/ui/public/agg_types/agg_type.js | 6 +- .../agg_types/buckets/_bucket_agg_type.js | 2 +- .../buckets/_bucket_count_between.js | 10 +- .../agg_types/buckets/_interval_options.js | 2 +- .../buckets/create_filter/date_histogram.js | 4 +- .../buckets/create_filter/date_range.js | 4 +- .../buckets/create_filter/filters.js | 4 +- .../buckets/create_filter/histogram.js | 2 +- src/ui/public/agg_types/buckets/date_range.js | 8 +- src/ui/public/agg_types/buckets/filters.js | 20 +- src/ui/public/agg_types/buckets/geo_hash.js | 2 +- src/ui/public/agg_types/buckets/histogram.js | 8 +- src/ui/public/agg_types/buckets/ip_range.js | 4 +- src/ui/public/agg_types/buckets/range.js | 18 +- .../agg_types/buckets/significant_terms.js | 4 +- src/ui/public/agg_types/buckets/terms.js | 38 ++-- src/ui/public/agg_types/index.js | 2 +- src/ui/public/agg_types/metrics/avg.js | 2 +- .../public/agg_types/metrics/cardinality.js | 4 +- src/ui/public/agg_types/metrics/count.js | 4 +- .../metrics/get_response_agg_config_class.js | 2 +- src/ui/public/agg_types/metrics/max.js | 2 +- src/ui/public/agg_types/metrics/median.js | 6 +- .../agg_types/metrics/metric_agg_type.js | 8 +- src/ui/public/agg_types/metrics/min.js | 2 +- .../agg_types/metrics/percentile_ranks.js | 14 +- .../public/agg_types/metrics/percentiles.js | 10 +- .../public/agg_types/metrics/std_deviation.js | 10 +- src/ui/public/agg_types/metrics/sum.js | 2 +- src/ui/public/agg_types/param_types/field.js | 4 +- .../public/agg_types/param_types/optioned.js | 2 +- .../public/agg_types/param_types/raw_json.js | 6 +- src/ui/public/agg_types/param_types/regex.js | 8 +- src/ui/public/agg_types/param_types/string.js | 2 +- src/ui/public/bind/__tests__/bind.js | 12 +- src/ui/public/bind/bind.js | 28 +-- src/ui/public/binder/__tests__/binder.js | 16 +- .../public/chrome/__tests__/nav_controls.js | 4 +- src/ui/public/chrome/api/angular.js | 6 +- src/ui/public/chrome/api/nav.js | 6 +- src/ui/public/chrome/api/theme.js | 4 +- .../app_switcher/__tests__/app_switcher.js | 44 ++-- .../collapsible_sidebar.js | 8 +- .../public/courier/_redirect_when_missing.js | 4 +- src/ui/public/courier/_request_queue.js | 2 +- src/ui/public/courier/courier.js | 26 +-- .../data_source/__tests__/decorate_query.js | 2 +- .../__tests__/normalize_sort_request.js | 34 +-- .../public/courier/data_source/_abstract.js | 38 ++-- .../courier/data_source/_decorate_query.js | 2 +- .../courier/data_source/_doc_send_to_es.js | 16 +- .../data_source/_normalize_sort_request.js | 8 +- .../data_source/_root_search_source.js | 6 +- .../public/courier/data_source/doc_source.js | 18 +- .../courier/data_source/search_source.js | 28 +-- src/ui/public/courier/looper/_looper.js | 4 +- src/ui/public/courier/looper/doc.js | 8 +- src/ui/public/courier/looper/search.js | 12 +- .../courier/saved_object/saved_object.js | 36 ++-- src/ui/public/debounce/__tests__/debounce.js | 16 +- src/ui/public/debounce/debounce.js | 6 +- .../__tests__/auto_select_if_only_one.js | 10 +- .../directives/__tests__/confirm-click.js | 2 +- .../directives/__tests__/css_truncate.js | 2 +- .../directives/__tests__/fixed_scroll.js | 24 +-- .../directives/__tests__/input_focus.js | 2 +- .../directives/__tests__/input_number.js | 6 +- .../public/directives/__tests__/json_input.js | 6 +- .../__tests__/paginated_selectable_list.js | 30 +-- .../directives/__tests__/parse_query.js | 6 +- .../public/directives/__tests__/timepicker.js | 20 +- .../public/directives/__tests__/truncate.js | 2 +- .../public/directives/__tests__/typeahead.js | 20 +- .../__tests__/validate_cidr_mask.js | 8 +- .../__tests__/validate_date_math.js | 8 +- .../__tests__/validate_index_name.js | 14 +- .../directives/__tests__/validate_ip.js | 8 +- .../directives/__tests__/validate_json.js | 12 +- .../directives/auto_select_if_only_one.js | 4 +- src/ui/public/directives/bread_crumbs.js | 2 +- src/ui/public/directives/click_focus.js | 4 +- src/ui/public/directives/confirm_click.js | 4 +- src/ui/public/directives/css_truncate.js | 2 +- src/ui/public/directives/field_name.js | 14 +- src/ui/public/directives/file_upload.js | 12 +- src/ui/public/directives/inequality.js | 8 +- src/ui/public/directives/infinite_scroll.js | 14 +- src/ui/public/directives/input_datetime.js | 10 +- src/ui/public/directives/input_focus.js | 2 +- src/ui/public/directives/input_number.js | 2 +- src/ui/public/directives/json_input.js | 2 +- src/ui/public/directives/paginate.js | 24 +-- src/ui/public/directives/pretty_duration.js | 16 +- src/ui/public/directives/rows.js | 20 +- .../public/directives/saved_object_finder.js | 22 +- .../public/directives/validate_date_math.js | 2 +- .../public/directives/validate_index_name.js | 4 +- src/ui/public/directives/validate_json.js | 2 +- .../public/doc_table/__tests__/doc_table.js | 4 +- .../doc_table/__tests__/lib/get_sort.js | 2 +- .../doc_table/__tests__/lib/rows_headers.js | 48 ++--- .../doc_table/components/table_header.js | 12 +- .../public/doc_table/components/table_row.js | 26 +-- src/ui/public/doc_table/doc_table.js | 8 +- src/ui/public/doc_table/lib/get_sort.js | 2 +- .../public/doc_title/__tests__/doc_title.js | 6 +- src/ui/public/doc_title/doc_title.js | 6 +- .../public/factories/__tests__/base_object.js | 14 +- src/ui/public/factories/__tests__/events.js | 56 ++--- src/ui/public/fancy_forms/fancy_forms.js | 8 +- .../public/fancy_forms/kbn_form_controller.js | 6 +- .../field_editor/__tests__/field_editor.js | 8 +- src/ui/public/field_editor/field_editor.js | 34 +-- .../field_format_editor.js | 20 +- .../field_format_editor/pattern/pattern.js | 2 +- .../field_format_editor/samples/samples.js | 6 +- .../filter_bar/__tests__/_add_filters.js | 14 +- .../filter_bar/__tests__/_get_filters.js | 26 +-- .../filter_bar/__tests__/_invert_filters.js | 4 +- .../filter_bar/__tests__/_pin_filters.js | 14 +- .../filter_bar/__tests__/_remove_filters.js | 6 +- .../filter_bar/__tests__/_toggle_filters.js | 4 +- .../filter_bar/__tests__/_update_filters.js | 2 +- .../public/filter_bar/__tests__/filter_bar.js | 10 +- .../filter_bar/__tests__/push_filter.js | 2 +- src/ui/public/filter_bar/filter_bar.js | 20 +- .../filter_bar/filter_bar_click_handler.js | 6 +- .../lib/__tests__/change_time_filter.js | 4 +- .../filter_bar/lib/__tests__/dedup_filters.js | 18 +- .../lib/__tests__/extract_time_filter.js | 4 +- .../__tests__/filter_applied_and_unwrap.js | 4 +- .../__tests__/filter_out_time_based_filter.js | 2 +- .../lib/__tests__/generate_mapping_chain.js | 52 ++--- .../lib/__tests__/map_and_flatten_filters.js | 2 +- .../filter_bar/lib/__tests__/map_default.js | 6 +- .../filter_bar/lib/__tests__/map_exists.js | 4 +- .../filter_bar/lib/__tests__/map_filter.js | 10 +- .../__tests__/map_flatten_and_wrap_filters.js | 2 +- .../lib/__tests__/map_geo_bounding_box.js | 4 +- .../filter_bar/lib/__tests__/map_missing.js | 4 +- .../lib/__tests__/map_query_string.js | 4 +- .../filter_bar/lib/__tests__/map_range.js | 6 +- .../filter_bar/lib/__tests__/map_script.js | 6 +- .../filter_bar/lib/__tests__/map_terms.js | 4 +- .../filter_bar/lib/__tests__/only_disabled.js | 40 ++-- .../filter_bar/lib/__tests__/uniq_filters.js | 12 +- .../filter_bar/lib/change_time_filter.js | 4 +- .../public/filter_bar/lib/compare_filters.js | 2 +- .../filter_bar/lib/extract_time_filter.js | 6 +- .../lib/filter_out_time_based_filter.js | 2 +- .../filter_bar/lib/generate_mapping_chain.js | 2 +- .../filter_bar/lib/map_and_flatten_filters.js | 2 +- src/ui/public/filter_bar/lib/map_default.js | 6 +- src/ui/public/filter_bar/lib/map_filter.js | 10 +- .../lib/map_flatten_and_wrap_filters.js | 2 +- src/ui/public/filter_bar/lib/map_range.js | 6 +- src/ui/public/filter_bar/lib/only_disabled.js | 2 +- .../filter_bar/lib/only_state_changed.js | 4 +- src/ui/public/filter_bar/push_filter.js | 4 +- src/ui/public/filter_bar/query_filter.js | 68 +++--- .../__tests__/filter_manager.js | 4 +- .../public/filter_manager/filter_manager.js | 14 +- .../filter_manager/lib/__tests__/range.js | 4 +- src/ui/public/filter_manager/lib/phrase.js | 2 +- src/ui/public/filters/__tests__/field_type.js | 4 +- src/ui/public/filters/__tests__/label.js | 2 +- src/ui/public/filters/__tests__/moment.js | 4 +- src/ui/public/filters/__tests__/rison.js | 6 +- src/ui/public/filters/__tests__/short_dots.js | 2 +- src/ui/public/filters/__tests__/start_from.js | 2 +- src/ui/public/filters/__tests__/uriescape.js | 2 +- src/ui/public/filters/_prop_filter.js | 8 +- src/ui/public/filters/comma_list.js | 4 +- src/ui/public/filters/rison.js | 2 +- src/ui/public/filters/trust_as_html.js | 2 +- src/ui/public/filters/unique.js | 2 +- .../public/highlight/__tests__/highlight.js | 18 +- src/ui/public/highlight/highlight.js | 6 +- src/ui/public/highlight/highlight_tags.js | 2 +- .../__tests__/_cast_mapping_type.js | 6 +- .../index_patterns/__tests__/_field_format.js | 48 ++--- .../__tests__/_index_pattern.js | 4 +- .../index_patterns/__tests__/_map_field.js | 14 +- .../__tests__/_pattern_to_wildcard.js | 2 +- .../index_patterns/__tests__/flatten_hit.js | 2 +- .../index_patterns/__tests__/intervals.js | 48 ++--- .../index_patterns/_cast_mapping_type.js | 2 +- src/ui/public/index_patterns/_ensure_some.js | 2 +- src/ui/public/index_patterns/_field.js | 24 +-- .../_field_format/content_types.js | 12 +- .../_field_format/field_format.js | 10 +- src/ui/public/index_patterns/_field_list.js | 2 +- src/ui/public/index_patterns/_flatten_hit.js | 8 +- src/ui/public/index_patterns/_format_hit.js | 10 +- .../index_patterns/_get_computed_fields.js | 4 +- src/ui/public/index_patterns/_get_ids.js | 2 +- src/ui/public/index_patterns/_intervals.js | 14 +- src/ui/public/index_patterns/_local_cache.js | 10 +- src/ui/public/index_patterns/_map_field.js | 8 +- src/ui/public/index_patterns/_mapper.js | 24 +-- .../public/index_patterns/_pattern_cache.js | 4 +- .../index_patterns/_pattern_to_wildcard.js | 2 +- .../_transform_mapping_into_fields.js | 10 +- .../public/index_patterns/index_patterns.js | 12 +- .../route_setup/load_default.js | 14 +- .../indexed_array/__tests__/indexed_array.js | 32 +-- .../indexed_array/__tests__/inflector.js | 12 +- src/ui/public/indexed_array/indexed_array.js | 22 +- src/ui/public/indexed_array/inflector.js | 2 +- .../jquery/__tests__/find_test_subject.js | 40 ++-- src/ui/public/jquery/find_test_subject.js | 2 +- .../__tests__/kbn_top_nav_controller.js | 4 +- src/ui/public/listen/__tests__/listen.js | 18 +- .../notify/__tests__/lib/_format_es_msg.js | 16 +- .../notify/__tests__/lib/_format_msg.js | 16 +- src/ui/public/notify/__tests__/notifier.js | 30 +-- src/ui/public/notify/directives.js | 2 +- src/ui/public/notify/errors.js | 6 +- src/ui/public/notify/lib/_format_es_msg.js | 4 +- src/ui/public/notify/lib/_format_msg.js | 4 +- src/ui/public/notify/notifier.js | 36 ++-- src/ui/public/notify/notify.js | 4 +- src/ui/public/number_list/number_list.js | 8 +- .../public/number_list/number_list_input.js | 42 ++-- .../public/paginated_table/__tests__/index.js | 62 +++--- src/ui/public/parse_query/lib/from_user.js | 4 +- src/ui/public/parse_query/parse_query.js | 4 +- .../public/pattern_checker/pattern_checker.js | 2 +- .../persisted_log/__tests__/persisted_log.js | 46 ++-- .../__tests__/persisted_state.js | 196 +++++++++--------- .../public/persisted_state/persisted_state.js | 50 ++--- src/ui/public/private/__tests__/private.js | 34 +-- src/ui/public/private/private.js | 16 +- src/ui/public/promises/__tests__/promises.js | 16 +- src/ui/public/promises/promises.js | 16 +- .../__tests__/reflow_watcher.js | 10 +- .../public/reflow_watcher/reflow_watcher.js | 10 +- src/ui/public/registry/__tests__/index.js | 34 +-- src/ui/public/registry/_registry.js | 12 +- src/ui/public/registry/field_formats.js | 8 +- .../public/routes/__tests__/_route_manager.js | 10 +- src/ui/public/routes/__tests__/_work_queue.js | 10 +- .../routes/__tests__/_wrap_route_with_prep.js | 6 +- src/ui/public/routes/route_manager.js | 14 +- src/ui/public/routes/route_setup_manager.js | 10 +- src/ui/public/routes/routes.js | 2 +- src/ui/public/routes/work_queue.js | 12 +- src/ui/public/routes/wrap_route_with_prep.js | 6 +- .../state_management/__tests__/app_state.js | 6 +- .../state_management/__tests__/state.js | 6 +- src/ui/public/state_management/app_state.js | 20 +- .../public/state_management/global_state.js | 4 +- src/ui/public/state_management/state.js | 10 +- src/ui/public/storage/__tests__/storage.js | 20 +- src/ui/public/storage/storage.js | 4 +- src/ui/public/stringify/__tests__/_color.js | 8 +- src/ui/public/stringify/__tests__/_date.js | 10 +- src/ui/public/stringify/__tests__/_source.js | 4 +- src/ui/public/stringify/__tests__/_string.js | 8 +- .../public/stringify/__tests__/_truncate.js | 16 +- src/ui/public/stringify/__tests__/_url.js | 30 +-- src/ui/public/stringify/types/_numeral.js | 6 +- src/ui/public/stringify/types/boolean.js | 2 +- src/ui/public/stringify/types/bytes.js | 2 +- src/ui/public/stringify/types/date.js | 14 +- src/ui/public/stringify/types/ip.js | 2 +- src/ui/public/stringify/types/number.js | 2 +- src/ui/public/stringify/types/percent.js | 4 +- src/ui/public/stringify/types/source.js | 18 +- src/ui/public/stringify/types/string.js | 2 +- src/ui/public/stringify/types/truncate.js | 6 +- src/ui/public/stringify/types/url.js | 16 +- .../style_compile/__tests__/style_compile.js | 2 +- src/ui/public/style_compile/style_compile.js | 8 +- .../template_vis_type/template_renderbot.js | 2 +- .../template_vis_type/template_vis_type.js | 4 +- .../public/time_buckets/calc_auto_interval.js | 14 +- .../public/time_buckets/calc_es_interval.js | 10 +- src/ui/public/time_buckets/time_buckets.js | 54 ++--- src/ui/public/timefilter/lib/diff_interval.js | 2 +- src/ui/public/timefilter/lib/diff_time.js | 2 +- src/ui/public/timefilter/timefilter.js | 24 +-- src/ui/public/timepicker/quick_ranges.js | 2 +- src/ui/public/timepicker/refresh_intervals.js | 2 +- src/ui/public/timepicker/time_units.js | 2 +- src/ui/public/timepicker/timepicker.js | 14 +- src/ui/public/typeahead/_input.js | 6 +- src/ui/public/typeahead/_items.js | 2 +- src/ui/public/typeahead/typeahead.js | 12 +- src/ui/public/url/__tests__/url.js | 86 ++++---- src/ui/public/url/url.js | 18 +- .../public/utils/__tests__/add_word_breaks.js | 6 +- src/ui/public/utils/__tests__/diff_object.js | 50 ++--- .../utils/__tests__/diff_time_picker_vals.js | 24 +-- src/ui/public/utils/__tests__/obj_define.js | 48 ++--- .../public/utils/__tests__/ordinal_suffix.js | 6 +- src/ui/public/utils/__tests__/range.js | 4 +- src/ui/public/utils/__tests__/scanner.js | 6 +- src/ui/public/utils/__tests__/sequencer.js | 2 +- .../public/utils/__tests__/simple_emitter.js | 20 +- src/ui/public/utils/__tests__/slugify_id.js | 6 +- src/ui/public/utils/add_word_breaks.js | 2 +- src/ui/public/utils/brush_event.js | 4 +- src/ui/public/utils/cidr_mask.js | 10 +- src/ui/public/utils/diff_object.js | 8 +- src/ui/public/utils/diff_time_picker_vals.js | 2 +- src/ui/public/utils/es_bool.js | 4 +- src/ui/public/utils/find_by_param.js | 2 +- src/ui/public/utils/ipv4_address.js | 10 +- src/ui/public/utils/mapping_setup.js | 12 +- src/ui/public/utils/no_white_space.js | 2 +- src/ui/public/utils/obj_define.js | 10 +- src/ui/public/utils/ordinal_suffix.js | 6 +- src/ui/public/utils/parse_interval.js | 12 +- src/ui/public/utils/query_string.js | 18 +- src/ui/public/utils/range.js | 8 +- src/ui/public/utils/scanner.js | 4 +- src/ui/public/utils/sequencer.js | 14 +- src/ui/public/utils/simple_emitter.js | 2 +- src/ui/public/utils/slugify_id.js | 4 +- src/ui/public/utils/supports.js | 10 +- src/ui/public/vis/__tests__/_agg_config.js | 92 ++++---- .../vis/__tests__/_agg_config_result.js | 40 ++-- src/ui/public/vis/__tests__/_agg_configs.js | 80 +++---- src/ui/public/vis/__tests__/_vis.js | 12 +- src/ui/public/vis/agg_config.js | 48 ++--- src/ui/public/vis/agg_configs.js | 20 +- src/ui/public/vis/schemas.js | 4 +- src/ui/public/vis/vis.js | 20 +- src/ui/public/vis/vis_type.js | 2 +- .../__tests__/_build_chart_data.js | 34 +-- .../__tests__/_vislib_renderbot.js | 36 ++-- .../vislib_vis_type/build_chart_data.js | 20 +- .../vislib_vis_type/vislib_renderbot.js | 18 +- .../public/vislib_vis_type/vislib_vis_type.js | 8 +- src/ui/public/visualize/spy.js | 16 +- src/ui/public/visualize/visualize.js | 34 +-- src/ui/public/visualize/visualize_legend.js | 30 +-- .../watch_multi/__tests__/watch_multi.js | 24 +-- src/ui/public/watch_multi/watch_multi.js | 12 +- src/ui/ui_bundle_collection.js | 4 +- src/ui/ui_bundler_env.js | 8 +- src/ui/ui_exports.js | 8 +- src/utils/collection.js | 2 +- src/utils/package_json.js | 2 +- tasks/build/babel_options.js | 8 +- tasks/build/index.js | 2 +- tasks/build/install_npm_deps.js | 4 +- tasks/build/package_json.js | 6 +- tasks/build/readme.js | 10 +- tasks/build/shasums.js | 12 +- tasks/build/versioned_links.js | 10 +- tasks/config/babel.js | 4 +- tasks/config/clean.js | 2 +- tasks/config/esvm.js | 8 +- tasks/config/intern.js | 2 +- tasks/config/platforms.js | 30 +-- tasks/config/run.js | 16 +- tasks/config/s3.js | 2 +- tasks/config/services.js | 4 +- tasks/licenses.js | 2 +- tasks/release.js | 2 +- tasks/release_packages.js | 2 +- tasks/sterilize.js | 2 +- tasks/utils/exec.js | 2 +- tasks/utils/install_or_update_repo.js | 6 +- tasks/utils/update_version.js | 12 +- test/fixtures/__tests__/scenario_manager.js | 34 +-- test/fixtures/config.js | 4 +- test/fixtures/scenario_manager.js | 26 +-- test/functional/apps/dashboard/_dashboard.js | 10 +- .../apps/discover/_collapse_expand.js | 4 +- test/functional/apps/discover/_field_data.js | 24 +-- .../functional/apps/discover/_shared_links.js | 12 +- .../apps/discover/_source_filters.js | 6 +- .../apps/management/_creation_form_changes.js | 8 +- .../_index_pattern_create_delete.js | 6 +- .../management/_index_pattern_popularity.js | 2 +- .../management/_index_pattern_results_sort.js | 2 +- .../apps/management/_initial_state.js | 2 +- test/functional/apps/visualize/_area_chart.js | 16 +- .../functional/apps/visualize/_chart_types.js | 2 +- test/functional/apps/visualize/_data_table.js | 10 +- test/functional/apps/visualize/_line_chart.js | 16 +- .../apps/visualize/_metric_chart.js | 24 +-- test/functional/apps/visualize/_pie_chart.js | 12 +- test/functional/apps/visualize/_tile_map.js | 16 +- .../apps/visualize/_vertical_bar_chart.js | 10 +- test/functional/apps/visualize/index.js | 2 +- test/functional/status_page/index.js | 4 +- test/mocha_setup.js | 6 +- test/server_config.js | 4 +- test/support/env_setup.js | 2 +- test/support/page_objects/common.js | 26 +-- test/support/page_objects/dashboard_page.js | 6 +- test/support/page_objects/discover_page.js | 2 +- test/support/page_objects/header_page.js | 2 +- test/support/page_objects/settings_page.js | 14 +- test/support/page_objects/shield_page.js | 2 +- test/support/page_objects/visualize_page.js | 36 ++-- test/support/utils/elastic_dump.js | 20 +- test/support/utils/es_client.js | 12 +- test/support/utils/try.js | 6 +- test/unit/api/ingest/_field_capabilities.js | 12 +- test/unit/api/ingest/_processors.js | 6 +- test/unit/api/ingest/_simulate.js | 8 +- test/unit/api/ingest/index.js | 22 +- test/unit/api/ingest/processors/_append.js | 6 +- test/unit/api/ingest/processors/_convert.js | 6 +- test/unit/api/ingest/processors/_date.js | 8 +- test/unit/api/ingest/processors/_geoip.js | 6 +- test/unit/api/ingest/processors/_grok.js | 6 +- test/unit/api/ingest/processors/_gsub.js | 6 +- test/unit/api/ingest/processors/_join.js | 6 +- test/unit/api/ingest/processors/_lowercase.js | 6 +- test/unit/api/ingest/processors/_remove.js | 6 +- test/unit/api/ingest/processors/_rename.js | 6 +- test/unit/api/ingest/processors/_set.js | 6 +- test/unit/api/ingest/processors/_split.js | 6 +- test/unit/api/ingest/processors/_trim.js | 6 +- test/unit/api/ingest/processors/_uppercase.js | 6 +- test/unit/api/ingest/processors/index.js | 28 +-- test/unit/api/scripts/_languages.js | 2 +- test/unit/api/scripts/index.js | 8 +- test/unit/api/search/_count.js | 6 +- test/unit/api/search/index.js | 12 +- test/utils/__tests__/get_page.js | 8 +- test/utils/get_url.js | 4 +- test/visual_regression/home/_loading.js | 2 +- 696 files changed, 4041 insertions(+), 4041 deletions(-) diff --git a/src/cli/cluster/worker.js b/src/cli/cluster/worker.js index 4108627edea65..320defcb7e0d5 100644 --- a/src/cli/cluster/worker.js +++ b/src/cli/cluster/worker.js @@ -5,16 +5,16 @@ import { EventEmitter } from 'events'; import { BinderFor, fromRoot } from '../../utils'; -let cliPath = fromRoot('src/cli'); -let baseArgs = _.difference(process.argv.slice(2), ['--no-watch']); -let baseArgv = [process.execPath, cliPath].concat(baseArgs); +const cliPath = fromRoot('src/cli'); +const baseArgs = _.difference(process.argv.slice(2), ['--no-watch']); +const baseArgv = [process.execPath, cliPath].concat(baseArgs); cluster.setupMaster({ exec: cliPath, silent: false }); -let dead = fork => { +const dead = fork => { return fork.isDead() || fork.killed; }; @@ -40,7 +40,7 @@ module.exports = class Worker extends EventEmitter { this.clusterBinder = new BinderFor(cluster); this.processBinder = new BinderFor(process); - let argv = _.union(baseArgv, opts.argv || []); + const argv = _.union(baseArgv, opts.argv || []); this.env = { kbnWorkerType: this.type, kbnWorkerArgv: JSON.stringify(argv) @@ -124,8 +124,8 @@ module.exports = class Worker extends EventEmitter { } flushChangeBuffer() { - let files = _.unique(this.changes.splice(0)); - let prefix = files.length > 1 ? '\n - ' : ''; + const files = _.unique(this.changes.splice(0)); + const prefix = files.length > 1 ? '\n - ' : ''; return files.reduce(function (list, file) { return `${list || ''}${prefix}"${file}"`; }, ''); diff --git a/src/cli/command.js b/src/cli/command.js index 135d03e32b6c1..98997f4bc1100 100644 --- a/src/cli/command.js +++ b/src/cli/command.js @@ -40,15 +40,15 @@ Command.prototype.unknownArgv = function (argv) { * @return {[type]} [description] */ Command.prototype.collectUnknownOptions = function () { - let title = `Extra ${this._name} options`; + const title = `Extra ${this._name} options`; this.allowUnknownOption(); this.getUnknownOptions = function () { - let opts = {}; - let unknowns = this.unknownArgv(); + const opts = {}; + const unknowns = this.unknownArgv(); while (unknowns.length) { - let opt = unknowns.shift().split('='); + const opt = unknowns.shift().split('='); if (opt[0].slice(0, 2) !== '--') { this.error(`${title} "${opt[0]}" must start with "--"`); } @@ -75,14 +75,14 @@ Command.prototype.collectUnknownOptions = function () { }; Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function (parse, argv) { - let opts = parse.call(this, argv); + const opts = parse.call(this, argv); this.unknownArgv(opts.unknown); return opts; }); Command.prototype.action = _.wrap(Command.prototype.action, function (action, fn) { return action.call(this, function (...args) { - let ret = fn.apply(this, args); + const ret = fn.apply(this, args); if (ret && typeof ret.then === 'function') { ret.then(null, function (e) { console.log('FATAL CLI ERROR', e.stack); diff --git a/src/cli/help.js b/src/cli/help.js index 89bc90a24cbd6..b5078aad458fe 100644 --- a/src/cli/help.js +++ b/src/cli/help.js @@ -5,12 +5,12 @@ module.exports = function (command, spaces) { return command.outputHelp(); } - let defCmd = _.find(command.commands, function (cmd) { + const defCmd = _.find(command.commands, function (cmd) { return cmd._name === 'serve'; }); - let desc = !command.description() ? '' : command.description(); - let cmdDef = !defCmd ? '' : `=${defCmd._name}`; + const desc = !command.description() ? '' : command.description(); + const cmdDef = !defCmd ? '' : `=${defCmd._name}`; return ( ` @@ -31,11 +31,11 @@ function indent(str, n) { } function commandsSummary(program) { - let cmds = _.compact(program.commands.map(function (cmd) { - let name = cmd._name; + const cmds = _.compact(program.commands.map(function (cmd) { + const name = cmd._name; if (name === '*') return; - let opts = cmd.options.length ? ' [options]' : ''; - let args = cmd._args.map(function (arg) { + const opts = cmd.options.length ? ' [options]' : ''; + const args = cmd._args.map(function (arg) { return humanReadableArgName(arg); }).join(' '); @@ -45,7 +45,7 @@ function commandsSummary(program) { ]; })); - let cmdLColWidth = cmds.reduce(function (width, cmd) { + const cmdLColWidth = cmds.reduce(function (width, cmd) { return Math.max(width, cmd[0].length); }, 0); @@ -69,6 +69,6 @@ ${indent(cmd.optionHelp(), 2)} } function humanReadableArgName(arg) { - let nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; } diff --git a/src/cli/log.js b/src/cli/log.js index bbbe3f2f21e89..50657ca533028 100644 --- a/src/cli/log.js +++ b/src/cli/log.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import ansicolors from 'ansicolors'; -let log = _.restParam(function (color, label, rest1) { +const log = _.restParam(function (color, label, rest1) { console.log.apply(console, [color(` ${_.trim(label)} `)].concat(rest1)); }); diff --git a/src/cli_plugin/cli.js b/src/cli_plugin/cli.js index 5a09416a9cb1a..3ff2ba328830f 100644 --- a/src/cli_plugin/cli.js +++ b/src/cli_plugin/cli.js @@ -5,8 +5,8 @@ import listCommand from './list'; import installCommand from './install'; import removeCommand from './remove'; -let argv = process.env.kbnWorkerArgv ? JSON.parse(process.env.kbnWorkerArgv) : process.argv.slice(); -let program = new Command('bin/kibana-plugin'); +const argv = process.env.kbnWorkerArgv ? JSON.parse(process.env.kbnWorkerArgv) : process.argv.slice(); +const program = new Command('bin/kibana-plugin'); program .version(pkg.version) @@ -23,7 +23,7 @@ program .command('help ') .description('get the help for a specific command') .action(function (cmdName) { - let cmd = _.find(program.commands, { _name: cmdName }); + const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); @@ -35,7 +35,7 @@ program }); // check for no command name -let subCommand = argv[2] && !String(argv[2][0]).match(/^-|^\.|\//); +const subCommand = argv[2] && !String(argv[2][0]).match(/^-|^\.|\//); if (!subCommand) { program.defaultHelp(); } diff --git a/src/cli_plugin/install/__tests__/index.js b/src/cli_plugin/install/__tests__/index.js index 470d9452a1c12..701247a49492e 100644 --- a/src/cli_plugin/install/__tests__/index.js +++ b/src/cli_plugin/install/__tests__/index.js @@ -8,7 +8,7 @@ describe('kibana cli', function () { describe('commander options', function () { - let program = { + const program = { command: function () { return program; }, description: function () { return program; }, option: function () { return program; }, diff --git a/src/cli_plugin/install/downloaders/file.js b/src/cli_plugin/install/downloaders/file.js index 505a103755e66..bd8233c009614 100644 --- a/src/cli_plugin/install/downloaders/file.js +++ b/src/cli_plugin/install/downloaders/file.js @@ -3,7 +3,7 @@ import { createWriteStream, createReadStream, unlinkSync, statSync } from 'fs'; function openSourceFile({ sourcePath }) { try { - let fileInfo = statSync(sourcePath); + const fileInfo = statSync(sourcePath); const readStream = createReadStream(sourcePath); diff --git a/src/cli_plugin/install/downloaders/http.js b/src/cli_plugin/install/downloaders/http.js index 40069c4cd063e..0b9844a6d9c14 100644 --- a/src/cli_plugin/install/downloaders/http.js +++ b/src/cli_plugin/install/downloaders/http.js @@ -53,7 +53,7 @@ export default async function downloadUrl(logger, sourceUrl, targetPath, timeout const { req, resp } = await sendRequest({ sourceUrl, timeout }); try { - let totalSize = parseFloat(resp.headers['content-length']) || 0; + const totalSize = parseFloat(resp.headers['content-length']) || 0; const progress = new Progress(logger); progress.init(totalSize); diff --git a/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js b/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js index 0e9b064393d15..7ab961a81a0ab 100644 --- a/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js +++ b/src/core_plugins/elasticsearch/lib/__tests__/is_upgradeable.js @@ -8,7 +8,7 @@ let version = pkg.version; describe('plugins/elasticsearch', function () { describe('lib/is_upgradeable', function () { - let server = { + const server = { config: _.constant({ get: function (key) { switch (key) { @@ -44,7 +44,7 @@ describe('plugins/elasticsearch', function () { upgradeDoc('5.0.0-alpha1', '5.0.0', false); it('should handle missing _id field', function () { - let doc = { + const doc = { '_index': '.kibana', '_type': 'config', '_score': 1, @@ -58,7 +58,7 @@ describe('plugins/elasticsearch', function () { }); it('should handle _id of @@version', function () { - let doc = { + const doc = { '_index': '.kibana', '_type': 'config', '_id': '@@version', diff --git a/src/core_plugins/kbn_doc_views/public/views/table.js b/src/core_plugins/kbn_doc_views/public/views/table.js index af201f39c3539..fef633e5827ec 100644 --- a/src/core_plugins/kbn_doc_views/public/views/table.js +++ b/src/core_plugins/kbn_doc_views/public/views/table.js @@ -26,7 +26,7 @@ docViewsRegistry.register(function () { }; $scope.showArrayInObjectsWarning = function (row, field) { - let value = $scope.flattened[field]; + const value = $scope.flattened[field]; return _.isArray(value) && typeof value[0] === 'object'; }; } diff --git a/src/core_plugins/kibana/index.js b/src/core_plugins/kibana/index.js index 85bc26a855046..210e656134e53 100644 --- a/src/core_plugins/kibana/index.js +++ b/src/core_plugins/kibana/index.js @@ -39,7 +39,7 @@ module.exports = function (kibana) { ], injectVars: function (server, options) { - let config = server.config(); + const config = server.config(); return { kbnDefaultAppId: config.get('kibana.defaultAppId'), tilemap: config.get('tilemap') diff --git a/src/core_plugins/kibana/public/dashboard/__tests__/dashboard_panels.js b/src/core_plugins/kibana/public/dashboard/__tests__/dashboard_panels.js index 0611c8eba587a..f74c0b3546523 100644 --- a/src/core_plugins/kibana/public/dashboard/__tests__/dashboard_panels.js +++ b/src/core_plugins/kibana/public/dashboard/__tests__/dashboard_panels.js @@ -36,7 +36,7 @@ describe('dashboard panels', function () { it('loads with no vizualizations', function () { ngMock.inject((SavedDashboard) => { - let dash = new SavedDashboard(); + const dash = new SavedDashboard(); dash.init(); compile(dash); }); @@ -45,7 +45,7 @@ describe('dashboard panels', function () { it('loads one vizualization', function () { ngMock.inject((SavedDashboard) => { - let dash = new SavedDashboard(); + const dash = new SavedDashboard(); dash.init(); dash.panelsJSON = `[{"col":3,"id":"foo1","row":1,"size_x":2,"size_y":2,"type":"visualization"}]`; compile(dash); @@ -55,7 +55,7 @@ describe('dashboard panels', function () { it('loads vizualizations in correct order', function () { ngMock.inject((SavedDashboard) => { - let dash = new SavedDashboard(); + const dash = new SavedDashboard(); dash.init(); dash.panelsJSON = `[ {"col":3,"id":"foo1","row":1,"size_x":2,"size_y":2,"type":"visualization"}, diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js index 8135fca9e1b4a..be9ecea4d89b3 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/directives/output_preview.js @@ -28,8 +28,8 @@ app.directive('outputPreview', function () { }); $scope.updateUi = function () { - let left = $scope.oldObject; - let right = $scope.newObject; + const left = $scope.oldObject; + const right = $scope.newObject; let delta = $scope.diffpatch.diff(left, right); if (!delta || $scope.error) delta = {}; diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js index 05f06927a4351..8995042138230 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/__tests__/keys_deep.js @@ -5,11 +5,11 @@ import keysDeep from '../keys_deep'; describe('keys deep', function () { it('should list first level properties', function () { - let object = { + const object = { property1: 'value1', property2: 'value2' }; - let expected = [ + const expected = [ 'property1', 'property2' ]; @@ -20,14 +20,14 @@ describe('keys deep', function () { }); it('should list nested properties', function () { - let object = { + const object = { property1: 'value1', property2: 'value2', property3: { subProperty1: 'value1.1' } }; - let expected = [ + const expected = [ 'property1', 'property2', 'property3.subProperty1', @@ -40,7 +40,7 @@ describe('keys deep', function () { }); it('should recursivly list nested properties', function () { - let object = { + const object = { property1: 'value1', property2: 'value2', property3: { @@ -52,7 +52,7 @@ describe('keys deep', function () { subProperty3: 'value1.3' } }; - let expected = [ + const expected = [ 'property1', 'property2', 'property3.subProperty1', @@ -69,11 +69,11 @@ describe('keys deep', function () { }); it('should list array properties, but not contents', function () { - let object = { + const object = { property1: 'value1', property2: [ 'item1', 'item2' ] }; - let expected = [ + const expected = [ 'property1', 'property2' ]; diff --git a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js index 5b5976583f132..a1f26d224dbc8 100644 --- a/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js +++ b/src/core_plugins/kibana/public/management/sections/indices/add_data_steps/pipeline_setup/lib/keys_deep.js @@ -2,10 +2,10 @@ import _ from 'lodash'; export default function keysDeep(object, base) { let result = []; - let delimitedBase = base ? base + '.' : ''; + const delimitedBase = base ? base + '.' : ''; _.forEach(object, (value, key) => { - let fullKey = delimitedBase + key; + const fullKey = delimitedBase + key; if (_.isPlainObject(value)) { result = result.concat(keysDeep(value, fullKey)); } else { diff --git a/src/core_plugins/kibana/public/visualize/editor/editor.js b/src/core_plugins/kibana/public/visualize/editor/editor.js index ea8bd1bbee123..b30d5a0f0cefa 100644 --- a/src/core_plugins/kibana/public/visualize/editor/editor.js +++ b/src/core_plugins/kibana/public/visualize/editor/editor.js @@ -139,7 +139,7 @@ function VisEditor($scope, $route, timefilter, AppState, $location, kbnUrl, $tim }; // Instance of app_state.js. - let $state = $scope.$state = (function initState() { + const $state = $scope.$state = (function initState() { // This is used to sync visualization state with the url when `appState.save()` is called. const appState = new AppState(stateDefaults); diff --git a/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js b/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js index 7444d38384638..6d83ee73f7645 100644 --- a/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js +++ b/src/core_plugins/kibana/server/lib/__tests__/create_mappings_from_pattern_fields.js @@ -36,7 +36,7 @@ describe('createMappingsFromPatternFields', function () { }); it('should set the same default mapping for all non-strings', function () { - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); _.forEach(mappings, function (mapping) { if (mapping.type !== 'text') { @@ -50,7 +50,7 @@ describe('createMappingsFromPatternFields', function () { }); it('should give strings a multi-field mapping with a "text" base type', function () { - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); _.forEach(mappings, function (mapping) { if (mapping.type === 'text') { @@ -61,7 +61,7 @@ describe('createMappingsFromPatternFields', function () { it('should handle nested fields', function () { testFields.push({name: 'geo.coordinates', type: 'geo_point'}); - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); expect(mappings).to.have.property('geo'); expect(mappings.geo).to.have.property('properties'); @@ -74,7 +74,7 @@ describe('createMappingsFromPatternFields', function () { }); it('should map all number fields as an ES double', function () { - let mappings = createMappingsFromPatternFields(testFields); + const mappings = createMappingsFromPatternFields(testFields); expect(mappings).to.have.property('bytes'); expect(mappings.bytes).to.have.property('type', 'double'); diff --git a/src/core_plugins/table_vis/public/table_vis_controller.js b/src/core_plugins/table_vis/public/table_vis_controller.js index fbd572a5e8575..df1b9aacfdc2a 100644 --- a/src/core_plugins/table_vis/public/table_vis_controller.js +++ b/src/core_plugins/table_vis/public/table_vis_controller.js @@ -11,7 +11,7 @@ const module = uiModules.get('kibana/table_vis', ['kibana']); module.controller('KbnTableVisController', function ($scope, Private) { const tabifyAggResponse = Private(AggResponseTabifyTabifyProvider); - let uiStateSort = ($scope.uiState) ? $scope.uiState.get('vis.params.sort') : {}; + const uiStateSort = ($scope.uiState) ? $scope.uiState.get('vis.params.sort') : {}; assign($scope.vis.params.sort, uiStateSort); $scope.sort = $scope.vis.params.sort; diff --git a/src/core_plugins/tests_bundle/find_source_files.js b/src/core_plugins/tests_bundle/find_source_files.js index c6b6151166cda..1a2938bbacd5d 100644 --- a/src/core_plugins/tests_bundle/find_source_files.js +++ b/src/core_plugins/tests_bundle/find_source_files.js @@ -5,7 +5,7 @@ import { resolve } from 'path'; import { map, fromNode } from 'bluebird'; import glob from 'glob-all'; -let findSourceFiles = async (patterns, cwd = fromRoot('.')) => { +const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { patterns = [].concat(patterns || []); const matches = await fromNode(cb => { diff --git a/src/core_plugins/tests_bundle/index.js b/src/core_plugins/tests_bundle/index.js index 34fe685e4602b..46f52ca91131b 100644 --- a/src/core_plugins/tests_bundle/index.js +++ b/src/core_plugins/tests_bundle/index.js @@ -16,7 +16,7 @@ export default (kibana) => { uiExports: { bundle: async (UiBundle, env, apps, plugins) => { let modules = []; - let config = kibana.config; + const config = kibana.config; const testGlobs = ['src/ui/public/**/*.js']; const testingPluginIds = config.get('tests_bundle.pluginId'); @@ -28,7 +28,7 @@ export default (kibana) => { if (!plugin) throw new Error('Invalid testingPluginId :: unknown plugin ' + pluginId); // add the modules from all of this plugins apps - for (let app of plugin.apps) { + for (const app of plugin.apps) { modules = union(modules, app.getModules()); } @@ -37,7 +37,7 @@ export default (kibana) => { } else { // add the modules from all of the apps - for (let app of apps) { + for (const app of apps) { modules = union(modules, app.getModules()); } @@ -47,7 +47,7 @@ export default (kibana) => { } const testFiles = await findSourceFiles(testGlobs); - for (let f of testFiles) modules.push(f); + for (const f of testFiles) modules.push(f); if (config.get('tests_bundle.instrument')) { env.addPostLoader({ diff --git a/src/core_plugins/timelion/index.js b/src/core_plugins/timelion/index.js index 51b8220a75001..e024abcf9aa4b 100644 --- a/src/core_plugins/timelion/index.js +++ b/src/core_plugins/timelion/index.js @@ -1,12 +1,12 @@ -let path = require('path'); +const path = require('path'); module.exports = function (kibana) { let mainFile = 'plugins/timelion/app'; - let ownDescriptor = Object.getOwnPropertyDescriptor(kibana, 'autoload'); - let protoDescriptor = Object.getOwnPropertyDescriptor(kibana.constructor.prototype, 'autoload'); - let descriptor = ownDescriptor || protoDescriptor || {}; + const ownDescriptor = Object.getOwnPropertyDescriptor(kibana, 'autoload'); + const protoDescriptor = Object.getOwnPropertyDescriptor(kibana.constructor.prototype, 'autoload'); + const descriptor = ownDescriptor || protoDescriptor || {}; if (descriptor.get) { // the autoload list has been replaced with a getter that complains about // improper access, bypass that getter by seeing if it is defined @@ -23,7 +23,7 @@ module.exports = function (kibana) { icon: 'plugins/timelion/icon.svg', main: mainFile, injectVars: function (server, options) { - let config = server.config(); + const config = server.config(); return { kbnIndex: config.get('kibana.index'), esShardTimeout: config.get('elasticsearch.shardTimeout'), diff --git a/src/core_plugins/timelion/init.js b/src/core_plugins/timelion/init.js index 5bd30de7de37d..c5362043d8334 100644 --- a/src/core_plugins/timelion/init.js +++ b/src/core_plugins/timelion/init.js @@ -1,5 +1,5 @@ -let _ = require('lodash'); -let processFunctionDefinition = require('./server/lib/process_function_definition'); +const _ = require('lodash'); +const processFunctionDefinition = require('./server/lib/process_function_definition'); module.exports = function (server) { //var config = server.config(); @@ -8,7 +8,7 @@ module.exports = function (server) { require('./server/routes/functions.js')(server); require('./server/routes/validate_es.js')(server); - let functions = require('./server/lib/load_functions')('series_functions'); + const functions = require('./server/lib/load_functions')('series_functions'); function addFunction(func) { _.assign(functions, processFunctionDefinition(func)); diff --git a/src/core_plugins/timelion/public/app.js b/src/core_plugins/timelion/public/app.js index adba360dba35d..a59fc60f10a58 100644 --- a/src/core_plugins/timelion/public/app.js +++ b/src/core_plugins/timelion/public/app.js @@ -1,6 +1,6 @@ -let _ = require('lodash'); -let logoUrl = require('./logo.png'); -let moment = require('moment-timezone'); +const _ = require('lodash'); +const logoUrl = require('./logo.png'); +const moment = require('moment-timezone'); require('plugins/timelion/directives/cells/cells'); require('plugins/timelion/directives/fullscreen/fullscreen'); @@ -15,7 +15,7 @@ document.title = 'Timelion - Kibana'; require('ui/chrome'); -let app = require('ui/modules').get('apps/timelion', []); +const app = require('ui/modules').get('apps/timelion', []); require('plugins/timelion/services/saved_sheets'); require('plugins/timelion/services/_saved_sheet'); @@ -27,7 +27,7 @@ require('./vis'); require('ui/saved_objects/saved_object_registry').register(require('plugins/timelion/services/saved_sheet_register')); // TODO: Expose an api for dismissing notifications -let unsafeNotifications = require('ui/notify')._notifs; +const unsafeNotifications = require('ui/notify')._notifs; //var ConfigTemplate = require('ui/config_template'); require('ui/routes').enable(); @@ -53,16 +53,16 @@ app.controller('timelion', function ( moment.tz.setDefault(config.get('dateFormat:tz')); timefilter.enabled = true; - let notify = new Notifier({ + const notify = new Notifier({ location: 'Timelion' }); - let timezone = Private(require('plugins/timelion/services/timezone'))(); - let docTitle = Private(require('ui/doc_title')); + const timezone = Private(require('plugins/timelion/services/timezone'))(); + const docTitle = Private(require('ui/doc_title')); - let defaultExpression = '.es(*)'; - let savedSheet = $route.current.locals.savedSheet; - let blankSheet = [defaultExpression]; + const defaultExpression = '.es(*)'; + const savedSheet = $route.current.locals.savedSheet; + const blankSheet = [defaultExpression]; $scope.topNavMenu = [{ key: 'new', @@ -109,7 +109,7 @@ app.controller('timelion', function ( }; } - let init = function () { + const init = function () { $scope.running = false; $scope.search(); @@ -192,7 +192,7 @@ app.controller('timelion', function ( $scope.sheet = []; $scope.running = false; - let err = new Error(resp.message); + const err = new Error(resp.message); err.stack = resp.stack; notify.error(err); diff --git a/src/core_plugins/timelion/public/directives/cells/cells.js b/src/core_plugins/timelion/public/directives/cells/cells.js index 40d1ecfbff99c..4046e6642d39f 100644 --- a/src/core_plugins/timelion/public/directives/cells/cells.js +++ b/src/core_plugins/timelion/public/directives/cells/cells.js @@ -1,12 +1,12 @@ -let _ = require('lodash'); -let $ = require('jquery'); +const _ = require('lodash'); +const $ = require('jquery'); require('angularSortableView'); require('plugins/timelion/directives/chart/chart'); require('plugins/timelion/directives/timelion_grid'); -let app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); -let html = require('./cells.html'); +const app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); +const html = require('./cells.html'); app.directive('timelionCells', function () { return { diff --git a/src/core_plugins/timelion/public/directives/chart/chart.js b/src/core_plugins/timelion/public/directives/chart/chart.js index cce425f7e7a6c..486a34fbc9027 100644 --- a/src/core_plugins/timelion/public/directives/chart/chart.js +++ b/src/core_plugins/timelion/public/directives/chart/chart.js @@ -1,4 +1,4 @@ -let panelRegistryProvider = require('plugins/timelion/lib/panel_registry'); +const panelRegistryProvider = require('plugins/timelion/lib/panel_registry'); require('ui/modules') .get('apps/timelion', []) @@ -12,7 +12,7 @@ require('ui/modules') }, link: function ($scope, $elem) { - let panelRegistry = Private(panelRegistryProvider); + const panelRegistry = Private(panelRegistryProvider); let panelScope = $scope.$new(true); function render(seriesList) { @@ -24,7 +24,7 @@ require('ui/modules') type: 'timechart' }; - let panelSchema = panelRegistry.byName[seriesList.render.type]; + const panelSchema = panelRegistry.byName[seriesList.render.type]; if (!panelSchema) { $elem.text('No such panel type: ' + seriesList.render.type); diff --git a/src/core_plugins/timelion/public/directives/docs.js b/src/core_plugins/timelion/public/directives/docs.js index a034f50461e9e..f8a155321299d 100644 --- a/src/core_plugins/timelion/public/directives/docs.js +++ b/src/core_plugins/timelion/public/directives/docs.js @@ -1,7 +1,7 @@ -let html = require('../partials/docs/tutorial.html'); -let app = require('ui/modules').get('apps/timelion', []); -let _ = require('lodash'); -let moment = require('moment'); +const html = require('../partials/docs/tutorial.html'); +const app = require('ui/modules').get('apps/timelion', []); +const _ = require('lodash'); +const moment = require('moment'); app.directive('timelionDocs', function (config, $http) { return { @@ -49,7 +49,7 @@ app.directive('timelionDocs', function (config, $http) { $scope.es.valid = false; $scope.es.invalidReason = (function () { try { - let esResp = JSON.parse(resp.data.resp.response); + const esResp = JSON.parse(resp.data.resp.response); return _.get(esResp, 'error.root_cause[0].reason'); } catch (e) { if (_.get(resp, 'data.resp.message')) return _.get(resp, 'data.resp.message'); diff --git a/src/core_plugins/timelion/public/directives/expression_directive.js b/src/core_plugins/timelion/public/directives/expression_directive.js index 8df3e1b15220b..63154d4dfcbcf 100644 --- a/src/core_plugins/timelion/public/directives/expression_directive.js +++ b/src/core_plugins/timelion/public/directives/expression_directive.js @@ -1,11 +1,11 @@ -let _ = require('lodash'); -let $ = require('jquery'); -let grammar = require('raw!../chain.peg'); -let PEG = require('pegjs'); -let Parser = PEG.buildParser(grammar); -let template = require('./partials/suggestion.html'); +const _ = require('lodash'); +const $ = require('jquery'); +const grammar = require('raw!../chain.peg'); +const PEG = require('pegjs'); +const Parser = PEG.buildParser(grammar); +const template = require('./partials/suggestion.html'); -let app = require('ui/modules').get('apps/timelion', []); +const app = require('ui/modules').get('apps/timelion', []); /* Autocomplete proposal, this file doesn't actually work like this @@ -40,7 +40,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc require: 'ngModel', link: function ($scope, $elem, $attrs, ngModelCtrl) { - let keys = { + const keys = { ESC: 27, UP: 38, DOWN: 40, @@ -48,7 +48,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc ENTER: 13 }; - let functionReference = {}; + const functionReference = {}; function init() { resetSuggestions(); @@ -81,7 +81,7 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc function suggest(val) { try { // Inside an existing function providing suggestion only as a reference. Maybe suggest an argument? - let possible = findFunction(getCaretPos(), Parser.parse(val).functions); + const possible = findFunction(getCaretPos(), Parser.parse(val).functions); // TODO: Reference suggestors. Only supporting completion right now; resetSuggestions(); return; @@ -124,20 +124,20 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc } function validateSelection() { - let maxSelection = $scope.suggestions.list.length - 1; + const maxSelection = $scope.suggestions.list.length - 1; if ($scope.suggestions.selected > maxSelection) $scope.suggestions.selected = maxSelection; else if ($scope.suggestions.selected < 0) $scope.suggestions.selected = 0; } $scope.completeExpression = function (selected) { if (!$scope.suggestions.list.length) return; - let expression = $attrs.timelionExpression; - let startOf = expression.slice(0, $scope.suggestions.location.min); - let endOf = expression.slice($scope.suggestions.location.max, expression.length); + const expression = $attrs.timelionExpression; + const startOf = expression.slice(0, $scope.suggestions.location.min); + const endOf = expression.slice($scope.suggestions.location.max, expression.length); - let completeFunction = $scope.suggestions.list[selected].name + '()'; + const completeFunction = $scope.suggestions.list[selected].name + '()'; - let newVal = startOf + completeFunction + endOf; + const newVal = startOf + completeFunction + endOf; $elem.val(newVal); $elem[0].selectionStart = $elem[0].selectionEnd = @@ -195,8 +195,8 @@ app.directive('timelionExpression', function ($compile, $http, $timeout, $rootSc function scrollTo(suggestions) { validateSelection(); - let suggestionsListElem = $('.suggestions'); - let suggestedElem = $($('.suggestion')[suggestions.selected]); + const suggestionsListElem = $('.suggestions'); + const suggestedElem = $($('.suggestion')[suggestions.selected]); if (!suggestedElem.position() || !suggestedElem.position().top) return; diff --git a/src/core_plugins/timelion/public/directives/fixed_element.js b/src/core_plugins/timelion/public/directives/fixed_element.js index d98a08a6eb9d8..1ba7ec123c2a1 100644 --- a/src/core_plugins/timelion/public/directives/fixed_element.js +++ b/src/core_plugins/timelion/public/directives/fixed_element.js @@ -1,16 +1,16 @@ -let _ = require('lodash'); -let $ = require('jquery'); +const _ = require('lodash'); +const $ = require('jquery'); -let app = require('ui/modules').get('apps/timelion', []); +const app = require('ui/modules').get('apps/timelion', []); app.directive('fixedElementRoot', function ($timeout) { return { restrict: 'A', link: function ($scope, $elem, attrs) { let fixedAt; $(window).bind('scroll', function () { - let fixed = $('[fixed-element]', $elem); - let body = $('[fixed-element-body]', $elem); - let top = fixed.offset().top; + const fixed = $('[fixed-element]', $elem); + const body = $('[fixed-element-body]', $elem); + const top = fixed.offset().top; if ($(window).scrollTop() > top) { // This is a gross hack, but its better than it was. I guess diff --git a/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js b/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js index ae60626ed5a3a..8d98776b8be62 100644 --- a/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js +++ b/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js @@ -1,12 +1,12 @@ -let _ = require('lodash'); -let $ = require('jquery'); +const _ = require('lodash'); +const $ = require('jquery'); require('angularSortableView'); require('plugins/timelion/directives/chart/chart'); require('plugins/timelion/directives/timelion_grid'); -let app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); -let html = require('./fullscreen.html'); +const app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); +const html = require('./fullscreen.html'); app.directive('timelionFullscreen', function () { return { diff --git a/src/core_plugins/timelion/public/directives/interval/interval.js b/src/core_plugins/timelion/public/directives/interval/interval.js index 28c2191b051bb..b168e0929f61e 100644 --- a/src/core_plugins/timelion/public/directives/interval/interval.js +++ b/src/core_plugins/timelion/public/directives/interval/interval.js @@ -1,9 +1,9 @@ -let _ = require('lodash'); -let $ = require('jquery'); -let moment = require('moment'); +const _ = require('lodash'); +const $ = require('jquery'); +const moment = require('moment'); -let app = require('ui/modules').get('apps/timelion', []); -let html = require('./interval.html'); +const app = require('ui/modules').get('apps/timelion', []); +const html = require('./interval.html'); app.directive('timelionInterval', function ($compile, $timeout, timefilter) { return { diff --git a/src/core_plugins/timelion/public/directives/refresh_hack.js b/src/core_plugins/timelion/public/directives/refresh_hack.js index 8a923ed623f1a..41d93ad6d089d 100644 --- a/src/core_plugins/timelion/public/directives/refresh_hack.js +++ b/src/core_plugins/timelion/public/directives/refresh_hack.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); -let $ = require('jquery'); +const _ = require('lodash'); +const $ = require('jquery'); -let app = require('ui/modules').get('apps/timelion', []); +const app = require('ui/modules').get('apps/timelion', []); app.directive('refreshHack', function ($rootScope) { return { diff --git a/src/core_plugins/timelion/public/directives/timelion_grid.js b/src/core_plugins/timelion/public/directives/timelion_grid.js index 0af069cd3167c..215c6ed576164 100644 --- a/src/core_plugins/timelion/public/directives/timelion_grid.js +++ b/src/core_plugins/timelion/public/directives/timelion_grid.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); -let $ = require('jquery'); +const _ = require('lodash'); +const $ = require('jquery'); -let app = require('ui/modules').get('apps/timelion', []); +const app = require('ui/modules').get('apps/timelion', []); app.directive('timelionGrid', function ($compile) { return { restrict: 'A', @@ -28,9 +28,9 @@ app.directive('timelionGrid', function ($compile) { }); function setDimensions() { - let borderSize = 2; - let headerSize = 45 + 35 + 28 + (20 * 2); // chrome + subnav + buttons + (container padding) - let verticalPadding = 10; + const borderSize = 2; + const headerSize = 45 + 35 + 28 + (20 * 2); // chrome + subnav + buttons + (container padding) + const verticalPadding = 10; if ($scope.timelionGridColumns != null) { $elem.width($elem.parent().width() / $scope.timelionGridColumns - (borderSize * 2)); diff --git a/src/core_plugins/timelion/public/panels/timechart/schema.js b/src/core_plugins/timelion/public/panels/timechart/schema.js index 5a01182ac51a9..6b182cb94e2be 100644 --- a/src/core_plugins/timelion/public/panels/timechart/schema.js +++ b/src/core_plugins/timelion/public/panels/timechart/schema.js @@ -1,25 +1,25 @@ require('./flot'); require('plugins/timelion/panels/timechart/timechart.less'); -let _ = require('lodash'); -let $ = require('jquery'); -let moment = require('moment-timezone'); -let observeResize = require('plugins/timelion/lib/observe_resize'); -let calculateInterval = require('plugins/timelion/lib/calculate_interval'); +const _ = require('lodash'); +const $ = require('jquery'); +const moment = require('moment-timezone'); +const observeResize = require('plugins/timelion/lib/observe_resize'); +const calculateInterval = require('plugins/timelion/lib/calculate_interval'); module.exports = function timechartFn(Private, config, $rootScope, timefilter, $compile) { return function () { return { help: 'Draw a timeseries chart', render: function ($scope, $elem) { - let template = '
'; - let timezone = Private(require('plugins/timelion/services/timezone'))(); - let getxAxisFormatter = Private(require('plugins/timelion/panels/timechart/xaxis_formatter')); + const template = '
'; + const timezone = Private(require('plugins/timelion/services/timezone'))(); + const getxAxisFormatter = Private(require('plugins/timelion/panels/timechart/xaxis_formatter')); // TODO: I wonder if we should supply our own moment that sets this every time? // could just use angular's injection to provide a moment service? moment.tz.setDefault(config.get('dateFormat:tz')); - let render = $scope.seriesList.render || {}; + const render = $scope.seriesList.render || {}; $scope.chart = $scope.seriesList.list; $scope.interval = $scope.interval; @@ -27,7 +27,7 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ let legendValueNumbers; let debouncedSetLegendNumbers; - let defaultOptions = { + const defaultOptions = { xaxis: { mode: 'time', tickLength: 5, @@ -65,12 +65,12 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ $scope.toggleSeries = function (id) { - let series = $scope.chart[id]; + const series = $scope.chart[id]; series._hide = !series._hide; drawPlot($scope.chart); }; - let cancelResize = observeResize($elem, function () { + const cancelResize = observeResize($elem, function () { drawPlot($scope.chart); }); @@ -108,7 +108,7 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ clearLegendNumbers(); }); - let debounceDelay = 50; + const debounceDelay = 50; debouncedSetLegendNumbers = _.debounce(setLegendNumbers, debounceDelay, { maxWait: debounceDelay, leading: true, @@ -117,20 +117,20 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ // Shamelessly borrowed from the flotCrosshairs example function setLegendNumbers(pos) { - let plot = $scope.plot; + const plot = $scope.plot; - let axes = plot.getAxes(); + const axes = plot.getAxes(); if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max) { return; } let i; let j; - let dataset = plot.getData(); + const dataset = plot.getData(); for (i = 0; i < dataset.length; ++i) { - let series = dataset[i]; - let precision = _.get(series, '_meta.precision', 2); + const series = dataset[i]; + const precision = _.get(series, '_meta.precision', 2); if (series._hide) continue; @@ -169,22 +169,22 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ } if (!$('.chart-canvas', $elem).length) $elem.html(template); - let canvasElem = $('.chart-canvas', $elem); + const canvasElem = $('.chart-canvas', $elem); - let title = _(plotConfig).map('_title').compact().last(); + const title = _(plotConfig).map('_title').compact().last(); $('.chart-top-title', $elem).text(title == null ? '' : title); - let options = _.cloneDeep(defaultOptions); + const options = _.cloneDeep(defaultOptions); // Get the X-axis tick format - let time = timefilter.getBounds(); - let interval = calculateInterval( + const time = timefilter.getBounds(); + const interval = calculateInterval( time.min.valueOf(), time.max.valueOf(), config.get('timelion:target_buckets') || 200, $scope.interval ); - let format = getxAxisFormatter(interval); + const format = getxAxisFormatter(interval); // Use moment to format ticks so we get timezone correction options.xaxis.tickFormatter = function (val) { @@ -192,11 +192,11 @@ module.exports = function timechartFn(Private, config, $rootScope, timefilter, $ }; // Calculate how many ticks can fit on the axis - let tickLetterWidth = 7; - let tickPadding = 45; + const tickLetterWidth = 7; + const tickPadding = 45; options.xaxis.ticks = Math.floor($elem.width() / ((format.length * tickLetterWidth) + tickPadding)); - let series = _.map(plotConfig, function (series, index) { + const series = _.map(plotConfig, function (series, index) { series = _.cloneDeep(_.defaults(series, { shadowSize: 0, lines: { diff --git a/src/core_plugins/timelion/public/panels/timechart/timechart.js b/src/core_plugins/timelion/public/panels/timechart/timechart.js index 8799aaccc2683..dcbb0d7e6e0f5 100644 --- a/src/core_plugins/timelion/public/panels/timechart/timechart.js +++ b/src/core_plugins/timelion/public/panels/timechart/timechart.js @@ -1,5 +1,5 @@ -let Panel = require('plugins/timelion/panels/panel'); -let panelRegistry = require('plugins/timelion/lib/panel_registry'); +const Panel = require('plugins/timelion/panels/panel'); +const panelRegistry = require('plugins/timelion/lib/panel_registry'); panelRegistry.register(function timeChartProvider(Private) { // Schema is broken out so that it may be extended for use in other plugins diff --git a/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js b/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js index 960999f91eed7..cd6a52a0b9c81 100644 --- a/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js +++ b/src/core_plugins/timelion/public/panels/timechart/xaxis_formatter.js @@ -1,18 +1,18 @@ -let moment = require('moment'); +const moment = require('moment'); module.exports = function xaxisFormatterProvider(config, timefilter) { function getFormat(esInterval) { - let parts = esInterval.match(/(\d+)(ms|s|m|h|d|w|M|y|)/); + const parts = esInterval.match(/(\d+)(ms|s|m|h|d|w|M|y|)/); if (parts == null || parts[1] == null || parts[2] == null) throw new Error ('Unknown interval'); - let interval = moment.duration(Number(parts[1]), parts[2]); + const interval = moment.duration(Number(parts[1]), parts[2]); // Cribbed from Kibana's TimeBuckets class - let rules = config.get('dateFormat:scaled'); + const rules = config.get('dateFormat:scaled'); for (let i = rules.length - 1; i >= 0; i--) { - let rule = rules[i]; + const rule = rules[i]; if (!rule[0] || interval >= moment.duration(rule[0])) { return rule[1]; } diff --git a/src/core_plugins/timelion/public/services/dashboard_context.js b/src/core_plugins/timelion/public/services/dashboard_context.js index 4c51b6018a839..d0f5a34362ae3 100644 --- a/src/core_plugins/timelion/public/services/dashboard_context.js +++ b/src/core_plugins/timelion/public/services/dashboard_context.js @@ -1,20 +1,20 @@ -let _ = require('lodash'); +const _ = require('lodash'); require('ui/state_management/app_state'); module.exports = function dashboardContext(Private, getAppState) { return function () { - let queryFilter = Private(require('ui/filter_bar/query_filter')); - let bool = {must: [], must_not: []}; - let filterBarFilters = queryFilter.getFilters(); - let queryBarFilter = getAppState().query; + const queryFilter = Private(require('ui/filter_bar/query_filter')); + const bool = {must: [], must_not: []}; + const filterBarFilters = queryFilter.getFilters(); + const queryBarFilter = getAppState().query; // Add the query bar filter, its handled differently. bool.must.push(queryBarFilter); // Add each of the filter bar filters _.each(filterBarFilters, function (filter) { - let esFilter = _.omit(filter, function (val, key) { + const esFilter = _.omit(filter, function (val, key) { if (key === 'meta' || key[0] === '$') return true; return false; }); diff --git a/src/core_plugins/timelion/public/services/saved_sheets.js b/src/core_plugins/timelion/public/services/saved_sheets.js index 6b73c9b3ea756..b402d78e4bf84 100644 --- a/src/core_plugins/timelion/public/services/saved_sheets.js +++ b/src/core_plugins/timelion/public/services/saved_sheets.js @@ -1,5 +1,5 @@ -let module = require('ui/modules').get('app/sheet'); -let _ = require('lodash'); +const module = require('ui/modules').get('app/sheet'); +const _ = require('lodash'); // bring in the factory require('./_saved_sheet.js'); @@ -40,7 +40,7 @@ module.service('savedSheets', function (Promise, SavedSheet, kbnIndex, es, kbnUr }; this.find = function (searchString) { - let self = this; + const self = this; let body; if (searchString) { body = { @@ -66,7 +66,7 @@ module.service('savedSheets', function (Promise, SavedSheet, kbnIndex, es, kbnUr return { total: resp.hits.total, hits: resp.hits.hits.map(function (hit) { - let source = hit._source; + const source = hit._source; source.id = hit._id; source.url = self.urlFor(hit._id); return source; diff --git a/src/core_plugins/timelion/public/vis/index.js b/src/core_plugins/timelion/public/vis/index.js index bd6843c671f43..6801b72aed908 100644 --- a/src/core_plugins/timelion/public/vis/index.js +++ b/src/core_plugins/timelion/public/vis/index.js @@ -9,7 +9,7 @@ require('plugins/timelion/vis/timelion_vis.less'); require('ui/registry/vis_types').register(TimelionVisProvider); function TimelionVisProvider(Private) { - let TemplateVisType = Private(require('ui/template_vis_type')); + const TemplateVisType = Private(require('ui/template_vis_type')); // return the visType object, which kibana will use to display and configure new // Vis object of this type. diff --git a/src/core_plugins/timelion/public/vis/timelion_vis_controller.js b/src/core_plugins/timelion/public/vis/timelion_vis_controller.js index fb47690f480fd..784b59923e55e 100644 --- a/src/core_plugins/timelion/public/vis/timelion_vis_controller.js +++ b/src/core_plugins/timelion/public/vis/timelion_vis_controller.js @@ -3,19 +3,19 @@ require('plugins/timelion/directives/interval/interval'); require('plugins/timelion/directives/refresh_hack'); require('ui/state_management/app_state'); -let _ = require('lodash'); -let module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); +const _ = require('lodash'); +const module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); module.controller('TimelionVisController', function ($scope, Private, Notifier, $http, $rootScope, timefilter, getAppState) { - let queryFilter = Private(require('ui/filter_bar/query_filter')); - let timezone = Private(require('plugins/timelion/services/timezone'))(); - let dashboardContext = Private(require('plugins/timelion/services/dashboard_context')); + const queryFilter = Private(require('ui/filter_bar/query_filter')); + const timezone = Private(require('plugins/timelion/services/timezone'))(); + const dashboardContext = Private(require('plugins/timelion/services/dashboard_context')); - let notify = new Notifier({ + const notify = new Notifier({ location: 'Timelion' }); $scope.search = function run() { - let expression = $scope.vis.params.expression; + const expression = $scope.vis.params.expression; if (!expression) return; $http.post('../api/timelion/run', { @@ -36,7 +36,7 @@ module.controller('TimelionVisController', function ($scope, Private, Notifier, }) .error(function (resp) { $scope.sheet = []; - let err = new Error(resp.message); + const err = new Error(resp.message); err.stack = resp.stack; notify.error(err); }); diff --git a/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js b/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js index 80a997b496a77..f4c0a8eac225b 100644 --- a/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js +++ b/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js @@ -1,6 +1,6 @@ require('plugins/timelion/directives/expression_directive'); -let module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); +const module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); module.controller('TimelionVisParamsController', function ($scope, $rootScope) { $scope.vis.params.expression = $scope.vis.params.expression || '.es(*)'; $scope.vis.params.interval = $scope.vis.params.interval || '1m'; diff --git a/src/core_plugins/timelion/server/fit_functions/__test__/average.js b/src/core_plugins/timelion/server/fit_functions/__test__/average.js index 606970fd8b8e0..b49221034ff73 100644 --- a/src/core_plugins/timelion/server/fit_functions/__test__/average.js +++ b/src/core_plugins/timelion/server/fit_functions/__test__/average.js @@ -1,20 +1,20 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); -let moment = require('moment'); -let expect = require('chai').expect; -let _ = require('lodash'); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); +const moment = require('moment'); +const expect = require('chai').expect; +const _ = require('lodash'); describe(filename, function () { describe('average', function () { it('fills holes in the data', function () { - let data = [ + const data = [ [moment.utc('1980', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 40], [moment.utc('1984', 'YYYY').valueOf(), 50], ]; - let target = [ + const target = [ [moment.utc('1980', 'YYYY').valueOf(), null], [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], @@ -27,13 +27,13 @@ describe(filename, function () { describe('sampling', function () { it('up', function () { - let data = [ + const data = [ [moment.utc('1981', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 30], [moment.utc('1985', 'YYYY').valueOf(), 70], ]; - let target = [ + const target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], @@ -46,7 +46,7 @@ describe(filename, function () { it('down', function () { - let data = [ + const data = [ [moment.utc('1980', 'YYYY').valueOf(), 0], [moment.utc('1981', 'YYYY').valueOf(), 2], [moment.utc('1982', 'YYYY').valueOf(), 4], @@ -56,7 +56,7 @@ describe(filename, function () { [moment.utc('1986', 'YYYY').valueOf(), 12], ]; - let target = [ + const target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], [moment.utc('1985', 'YYYY').valueOf(), null], diff --git a/src/core_plugins/timelion/server/fit_functions/__test__/carry.js b/src/core_plugins/timelion/server/fit_functions/__test__/carry.js index 53a71bfaee2a0..68cce07ee0ec5 100644 --- a/src/core_plugins/timelion/server/fit_functions/__test__/carry.js +++ b/src/core_plugins/timelion/server/fit_functions/__test__/carry.js @@ -1,18 +1,18 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); -let moment = require('moment'); -let expect = require('chai').expect; -let _ = require('lodash'); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); +const moment = require('moment'); +const expect = require('chai').expect; +const _ = require('lodash'); describe(filename, function () { it('fills holes in the data', function () { - let data = [ + const data = [ [moment.utc('1980', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 40], [moment.utc('1984', 'YYYY').valueOf(), 50], ]; - let target = [ + const target = [ [moment.utc('1980', 'YYYY').valueOf(), null], [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], @@ -25,13 +25,13 @@ describe(filename, function () { describe('sampling', function () { it('up', function () { - let data = [ + const data = [ [moment.utc('1981', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 30], [moment.utc('1985', 'YYYY').valueOf(), 70], ]; - let target = [ + const target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1982', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], @@ -44,7 +44,7 @@ describe(filename, function () { it('down does not make sense', function () { - let data = [ + const data = [ [moment.utc('1980', 'YYYY').valueOf(), 0], [moment.utc('1981', 'YYYY').valueOf(), 2], [moment.utc('1982', 'YYYY').valueOf(), 4], @@ -54,7 +54,7 @@ describe(filename, function () { [moment.utc('1986', 'YYYY').valueOf(), 12], ]; - let target = [ + const target = [ [moment.utc('1981', 'YYYY').valueOf(), null], [moment.utc('1983', 'YYYY').valueOf(), null], [moment.utc('1985', 'YYYY').valueOf(), null], diff --git a/src/core_plugins/timelion/server/fit_functions/average.js b/src/core_plugins/timelion/server/fit_functions/average.js index 03eb77e7a9f5c..3cbd0e1d12249 100644 --- a/src/core_plugins/timelion/server/fit_functions/average.js +++ b/src/core_plugins/timelion/server/fit_functions/average.js @@ -1,4 +1,4 @@ -let _ = require('lodash'); +const _ = require('lodash'); // Upsampling and down sampling of non-cummulative sets // Good: min, max, average @@ -9,12 +9,12 @@ module.exports = function (dataTuples, targetTuples) { // Phase 1: Downsample // We nessecarily won't well match the dataSource here as we don't know how much data // they had when creating their own average - let resultTimes = _.pluck(targetTuples, 0); - let dataTuplesQueue = _.clone(dataTuples); - let resultValues = _.map(targetTuples, function (bucket) { - let time = bucket[0]; + const resultTimes = _.pluck(targetTuples, 0); + const dataTuplesQueue = _.clone(dataTuples); + const resultValues = _.map(targetTuples, function (bucket) { + const time = bucket[0]; let i = 0; - let avgSet = []; + const avgSet = []; // This is naive, it doesn't consider where the line is going next, // It simply writes the point and moves on once it hits <= time. @@ -27,7 +27,7 @@ module.exports = function (dataTuples, targetTuples) { dataTuplesQueue.splice(0, i); - let sum = _.reduce(avgSet, function (sum, num) { return sum + num; }, 0); + const sum = _.reduce(avgSet, function (sum, num) { return sum + num; }, 0); return avgSet.length ? (sum / avgSet.length) : NaN; }); @@ -35,14 +35,14 @@ module.exports = function (dataTuples, targetTuples) { // Phase 2: Upsample if needed // If we have any NaNs we are probably resampling from a big interval to a small one (eg, 1M as 1d) // So look for the missing stuff in the array, and smooth it out - let naNIndex = _.findIndex(resultValues, function (val) { + const naNIndex = _.findIndex(resultValues, function (val) { return isNaN(val); }); if (naNIndex > -1) { let i = 0; let naNCount = 0; - let filledValues = []; + const filledValues = []; let previousRealNumber; let stepSize; while (i < resultValues.length) { @@ -70,6 +70,6 @@ module.exports = function (dataTuples, targetTuples) { } - let resultTuples = _.zip(resultTimes, resultValues); + const resultTuples = _.zip(resultTimes, resultValues); return resultTuples; }; diff --git a/src/core_plugins/timelion/server/fit_functions/carry.js b/src/core_plugins/timelion/server/fit_functions/carry.js index 75fadc2f7543b..297c1288b771e 100644 --- a/src/core_plugins/timelion/server/fit_functions/carry.js +++ b/src/core_plugins/timelion/server/fit_functions/carry.js @@ -1,5 +1,5 @@ -let _ = require('lodash'); -let moment = require('moment'); +const _ = require('lodash'); +const moment = require('moment'); // Upsampling of non-cummulative sets // Good: average, min, max @@ -14,8 +14,8 @@ module.exports = function (dataTuples, targetTuples) { let currentCarry = dataTuples[0][1]; return _.map(targetTuples, function (bucket, h) { - let targetTime = bucket[0]; - let dataTime = dataTuples[0][0]; + const targetTime = bucket[0]; + const dataTime = dataTuples[0][0]; if (dataTuples[0] && targetTime >= dataTime) { currentCarry = dataTuples[0][1]; diff --git a/src/core_plugins/timelion/server/fit_functions/nearest.js b/src/core_plugins/timelion/server/fit_functions/nearest.js index 65d528e6e9508..c3d639edfef1d 100644 --- a/src/core_plugins/timelion/server/fit_functions/nearest.js +++ b/src/core_plugins/timelion/server/fit_functions/nearest.js @@ -1,12 +1,12 @@ -let _ = require('lodash'); -let moment = require('moment'); +const _ = require('lodash'); +const moment = require('moment'); // Upsampling and downsampling of non-cummulative sets // Good: average, min, max // Bad: sum, count module.exports = function (dataTuples, targetTuples) { return _.map(targetTuples, function (bucket, h) { - let time = bucket[0]; + const time = bucket[0]; let i = 0; while (i < dataTuples.length - 1 && (Math.abs(dataTuples[i + 1][0] - time) < Math.abs(dataTuples[i][0] - time) || @@ -20,7 +20,7 @@ module.exports = function (dataTuples, targetTuples) { i++; } - let closest = dataTuples[i]; + const closest = dataTuples[i]; dataTuples.splice(0, i); return [bucket[0], closest[1]]; diff --git a/src/core_plugins/timelion/server/fit_functions/scale.js b/src/core_plugins/timelion/server/fit_functions/scale.js index 5da08aef11e09..d5105f381038f 100644 --- a/src/core_plugins/timelion/server/fit_functions/scale.js +++ b/src/core_plugins/timelion/server/fit_functions/scale.js @@ -1,4 +1,4 @@ -let _ = require('lodash'); +const _ = require('lodash'); // Downsampling of cummulative metrics // Good: count, sum @@ -18,7 +18,7 @@ module.exports = function (dataTuples, targetTuples) { let i = 0; let j = 0; let spreadCount = 0; - let result = []; + const result = []; let bucket; let time; let scaleSet; diff --git a/src/core_plugins/timelion/server/handlers/chain_runner.js b/src/core_plugins/timelion/server/handlers/chain_runner.js index 993bcdfd68fab..3cd056bb961cf 100644 --- a/src/core_plugins/timelion/server/handlers/chain_runner.js +++ b/src/core_plugins/timelion/server/handlers/chain_runner.js @@ -1,24 +1,24 @@ -let _ = require('lodash'); -let glob = require('glob'); -let Promise = require('bluebird'); +const _ = require('lodash'); +const glob = require('glob'); +const Promise = require('bluebird'); -let parseSheet = require('./lib/parse_sheet.js'); -let parseDateMath = require('../lib/date_math.js'); -let calculateInterval = require('../../public/lib/calculate_interval.js'); +const parseSheet = require('./lib/parse_sheet.js'); +const parseDateMath = require('../lib/date_math.js'); +const calculateInterval = require('../../public/lib/calculate_interval.js'); -let repositionArguments = require('./lib/reposition_arguments.js'); -let indexArguments = require('./lib/index_arguments.js'); -let validateTime = require('./lib/validate_time.js'); +const repositionArguments = require('./lib/reposition_arguments.js'); +const indexArguments = require('./lib/index_arguments.js'); +const validateTime = require('./lib/validate_time.js'); -let loadFunctions = require('../lib/load_functions.js'); -let fitFunctions = loadFunctions('fit_functions'); +const loadFunctions = require('../lib/load_functions.js'); +const fitFunctions = loadFunctions('fit_functions'); module.exports = function (tlConfig) { - let preprocessChain = require('./lib/preprocess_chain')(tlConfig); + const preprocessChain = require('./lib/preprocess_chain')(tlConfig); let queryCache = {}; - let stats = {}; + const stats = {}; let sheet; function getQueryCacheKey(query) { @@ -31,7 +31,7 @@ module.exports = function (tlConfig) { // Invokes a modifier function, resolving arguments into series as needed function invoke(fnName, args) { - let functionDef = tlConfig.server.plugins.timelion.getFunction(fnName); + const functionDef = tlConfig.server.plugins.timelion.getFunction(fnName); function resolveArgument(item) { if (_.isArray(item)) { @@ -87,8 +87,8 @@ module.exports = function (tlConfig) { function invokeChain(chainObj, result) { if (chainObj.chain.length === 0) return result[0]; - let chain = _.clone(chainObj.chain); - let link = chain.shift(); + const chain = _.clone(chainObj.chain); + const link = chain.shift(); let promise; if (link.type === 'chain') { @@ -96,7 +96,7 @@ module.exports = function (tlConfig) { } else if (!result) { promise = invoke('first', [link]); } else { - let args = link.arguments ? result.concat(link.arguments) : result; + const args = link.arguments ? result.concat(link.arguments) : result; promise = invoke(link.function, args); } @@ -107,15 +107,15 @@ module.exports = function (tlConfig) { } function resolveChainList(chainList) { - let seriesList = _.map(chainList, function (chain) { - let values = invoke('first', [chain]); + const seriesList = _.map(chainList, function (chain) { + const values = invoke('first', [chain]); return values.then(function (args) { return args; }); }); return Promise.all(seriesList).then(function (args) { - let list = _.chain(args).pluck('list').flatten().value(); - let seriesList = _.merge.apply(this, _.flatten([{}, args])); + const list = _.chain(args).pluck('list').flatten().value(); + const seriesList = _.merge.apply(this, _.flatten([{}, args])); seriesList.list = list; return seriesList; }); @@ -126,7 +126,7 @@ module.exports = function (tlConfig) { let queries = {}; _.each(sheet, function (chainList, i) { try { - let queriesInCell = _.mapValues(preprocessChain(chainList), function (val) { + const queriesInCell = _.mapValues(preprocessChain(chainList), function (val) { val.cell = i; return val; }); @@ -137,7 +137,7 @@ module.exports = function (tlConfig) { }); queries = _.values(queries); - let promises = _.chain(queries).values().map(function (query) { + const promises = _.chain(queries).values().map(function (query) { return invoke(query.function, query.arguments); }).value(); @@ -146,8 +146,8 @@ module.exports = function (tlConfig) { stats.queryTime = (new Date()).getTime(); _.each(queries, function (query, i) { - let functionDef = tlConfig.server.plugins.timelion.getFunction(query.function); - let resolvedDatasource = resolvedDatasources[i]; + const functionDef = tlConfig.server.plugins.timelion.getFunction(query.function); + const resolvedDatasource = resolvedDatasources[i]; if (resolvedDatasource.isRejected()) { if (resolvedDatasource.reason().isBoom) { diff --git a/src/core_plugins/timelion/server/handlers/lib/arg_type.js b/src/core_plugins/timelion/server/handlers/lib/arg_type.js index d034426551e21..99fe2115d617d 100644 --- a/src/core_plugins/timelion/server/handlers/lib/arg_type.js +++ b/src/core_plugins/timelion/server/handlers/lib/arg_type.js @@ -1,4 +1,4 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function argType(arg) { if (_.isArray(arg)) { diff --git a/src/core_plugins/timelion/server/handlers/lib/index_arguments.js b/src/core_plugins/timelion/server/handlers/lib/index_arguments.js index e90f84777e8cb..2d3a7c2e8824e 100644 --- a/src/core_plugins/timelion/server/handlers/lib/index_arguments.js +++ b/src/core_plugins/timelion/server/handlers/lib/index_arguments.js @@ -1,26 +1,26 @@ -let _ = require('lodash'); +const _ = require('lodash'); // Only applies to already resolved arguments module.exports = function indexArguments(functionDef, orderedArgs) { - let validateArg = require('./validate_arg')(functionDef); + const validateArg = require('./validate_arg')(functionDef); // This almost certainly is not required - let allowedLength = functionDef.extended ? functionDef.args.length + 2 : functionDef.args.length; + const allowedLength = functionDef.extended ? functionDef.args.length + 2 : functionDef.args.length; if (orderedArgs.length > allowedLength) throw new Error ('Too many arguments passed to: ' + functionDef.name); - let indexedArgs = {}; + const indexedArgs = {}; // Check and index each known argument _.each(functionDef.args, function (argDef, i) { - let value = orderedArgs[i]; + const value = orderedArgs[i]; validateArg(value, argDef.name, argDef); indexedArgs[argDef.name] = value; }); // Also check and index the extended arguments if enabled if (functionDef.extended) { - let values = orderedArgs[orderedArgs.length - 1]; - let names = orderedArgs[orderedArgs.length - 2]; + const values = orderedArgs[orderedArgs.length - 1]; + const names = orderedArgs[orderedArgs.length - 2]; _.each(values, function (value, i) { validateArg(value, names[i], functionDef.extended); indexedArgs[names[i]] = value; diff --git a/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js b/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js index 35f2fd490bb55..d89376dec7ec9 100644 --- a/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js +++ b/src/core_plugins/timelion/server/handlers/lib/parse_sheet.js @@ -1,9 +1,9 @@ -let fs = require('fs'); -let path = require('path'); -let _ = require('lodash'); -let grammar = fs.readFileSync(path.resolve(__dirname, '../../../public/chain.peg'), 'utf8'); -let PEG = require('pegjs'); -let Parser = PEG.buildParser(grammar); +const fs = require('fs'); +const path = require('path'); +const _ = require('lodash'); +const grammar = fs.readFileSync(path.resolve(__dirname, '../../../public/chain.peg'), 'utf8'); +const PEG = require('pegjs'); +const Parser = PEG.buildParser(grammar); module.exports = function parseSheet(sheet) { return _.map(sheet, function (plot) { diff --git a/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js b/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js index 2e1d1360285bd..5223d6fba9977 100644 --- a/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js +++ b/src/core_plugins/timelion/server/handlers/lib/preprocess_chain.js @@ -1,11 +1,11 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function preProcessChainFn(tlConfig) { return function preProcessChain(chain, queries) { queries = queries || {}; function validateAndStore(item) { if (_.isObject(item) && item.type === 'function') { - let functionDef = tlConfig.server.plugins.timelion.getFunction(item.function); + const functionDef = tlConfig.server.plugins.timelion.getFunction(item.function); if (functionDef.datasource) { queries[functionDef.cacheKey(item)] = item; diff --git a/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js b/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js index ac2a81fc312e9..8638645d23f24 100644 --- a/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js +++ b/src/core_plugins/timelion/server/handlers/lib/reposition_arguments.js @@ -1,8 +1,8 @@ -let _ = require('lodash'); +const _ = require('lodash'); // Applies to unresolved arguments in the AST module.exports = function repositionArguments(functionDef, unorderedArgs) { - let args = []; + const args = []; _.each(unorderedArgs, function (unorderedArg, i) { let argDef; @@ -15,7 +15,7 @@ module.exports = function repositionArguments(functionDef, unorderedArgs) { if (!argDef) { if (functionDef.extended) { - let namesIndex = functionDef.args.length; + const namesIndex = functionDef.args.length; targetIndex = functionDef.args.length + 1; args[namesIndex] = args[namesIndex] || []; diff --git a/src/core_plugins/timelion/server/handlers/lib/tl_config.js b/src/core_plugins/timelion/server/handlers/lib/tl_config.js index dea23f85b3476..f253001a89bce 100644 --- a/src/core_plugins/timelion/server/handlers/lib/tl_config.js +++ b/src/core_plugins/timelion/server/handlers/lib/tl_config.js @@ -1,6 +1,6 @@ -let _ = require('lodash'); +const _ = require('lodash'); -let buildTarget = require('../../lib/build_target.js'); +const buildTarget = require('../../lib/build_target.js'); module.exports = function (setup) { let targetSeries; diff --git a/src/core_plugins/timelion/server/handlers/lib/validate_arg.js b/src/core_plugins/timelion/server/handlers/lib/validate_arg.js index 79464b5eaaff6..cd11a679ae23b 100644 --- a/src/core_plugins/timelion/server/handlers/lib/validate_arg.js +++ b/src/core_plugins/timelion/server/handlers/lib/validate_arg.js @@ -1,12 +1,12 @@ -let argType = require('./arg_type'); -let _ = require('lodash'); +const argType = require('./arg_type'); +const _ = require('lodash'); module.exports = function (functionDef) { return function validateArg(value, name, argDef) { - let type = argType(value); - let required = argDef.types; - let multi = argDef.multi; - let isCorrectType = (function () { + const type = argType(value); + const required = argDef.types; + const multi = argDef.multi; + const isCorrectType = (function () { // If argument is not allow to be specified multiple times, we're dealing with a plain value for type if (!multi) return _.contains(required, type); // If it is, we'll get an array for type diff --git a/src/core_plugins/timelion/server/handlers/lib/validate_time.js b/src/core_plugins/timelion/server/handlers/lib/validate_time.js index 284788170feb2..b28e46d254882 100644 --- a/src/core_plugins/timelion/server/handlers/lib/validate_time.js +++ b/src/core_plugins/timelion/server/handlers/lib/validate_time.js @@ -1,11 +1,11 @@ -let parseDateMath = require('../../lib/date_math.js'); -let toMS = require('../../lib/to_milliseconds.js'); +const parseDateMath = require('../../lib/date_math.js'); +const toMS = require('../../lib/to_milliseconds.js'); module.exports = function validateTime(time, tlConfig) { - let span = parseDateMath(time.to, true) - parseDateMath(time.from); - let interval = toMS(time.interval); - let bucketCount = span / interval; - let maxBuckets = tlConfig.settings['timelion:max_buckets']; + const span = parseDateMath(time.to, true) - parseDateMath(time.from); + const interval = toMS(time.interval); + const bucketCount = span / interval; + const maxBuckets = tlConfig.settings['timelion:max_buckets']; if (bucketCount > maxBuckets) { throw new Error('Max buckets exceeded: ' + Math.round(bucketCount) + ' of ' + maxBuckets + ' allowed. ' + diff --git a/src/core_plugins/timelion/server/lib/__test__/load_functions.js b/src/core_plugins/timelion/server/lib/__test__/load_functions.js index 9f4aaea8124ee..aa4ab70d2fe3a 100644 --- a/src/core_plugins/timelion/server/lib/__test__/load_functions.js +++ b/src/core_plugins/timelion/server/lib/__test__/load_functions.js @@ -1,8 +1,8 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); -let _ = require('lodash'); -let expect = require('chai').expect; +const _ = require('lodash'); +const expect = require('chai').expect; describe(filename, () => { it('exports a function', () => { @@ -10,14 +10,14 @@ describe(filename, () => { }); it('returns an object with keys named for the javascript files in the directory', () => { - let fnList = fn('series_functions'); + const fnList = fn('series_functions'); expect(fnList).to.be.an('object'); expect(fnList.sum).to.be.a('object'); }); it('also includes index.js files in direct subdirectories, and names the keys for the directory', () => { - let fnList = fn('series_functions'); + const fnList = fn('series_functions'); expect(fnList).to.be.an('object'); expect(fnList.es).to.be.a('object'); diff --git a/src/core_plugins/timelion/server/lib/alter.js b/src/core_plugins/timelion/server/lib/alter.js index 3168ccfbe29cc..39f0043e116ce 100644 --- a/src/core_plugins/timelion/server/lib/alter.js +++ b/src/core_plugins/timelion/server/lib/alter.js @@ -1,5 +1,5 @@ -let Promise = require('bluebird'); -let _ = require('lodash'); +const Promise = require('bluebird'); +const _ = require('lodash'); /* @param {Array} args * - args[0] must be a seriesList @@ -12,13 +12,13 @@ module.exports = function alter(args, fn) { // In theory none of the args should ever be promises. This is probably a waste. return Promise.all(args).then(function (args) { - let seriesList = args.shift(); + const seriesList = args.shift(); if (seriesList.type !== 'seriesList') { throw new Error ('args[0] must be a seriesList'); } - let list = _.chain(seriesList.list).map(function (series) { + const list = _.chain(seriesList.list).map(function (series) { return fn.apply(this, [series].concat(args)); }).flatten().value(); diff --git a/src/core_plugins/timelion/server/lib/asSorted.js b/src/core_plugins/timelion/server/lib/asSorted.js index b7ae85b36278f..54932484e871d 100644 --- a/src/core_plugins/timelion/server/lib/asSorted.js +++ b/src/core_plugins/timelion/server/lib/asSorted.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); -let unzipPairs = require('./unzipPairs.js'); +const _ = require('lodash'); +const unzipPairs = require('./unzipPairs.js'); module.exports = function asSorted(timeValObject, fn) { - let data = unzipPairs(timeValObject); + const data = unzipPairs(timeValObject); return _.zipObject(fn(data)); }; diff --git a/src/core_plugins/timelion/server/lib/build_target.js b/src/core_plugins/timelion/server/lib/build_target.js index af23589edf7e9..2aada71e4accb 100644 --- a/src/core_plugins/timelion/server/lib/build_target.js +++ b/src/core_plugins/timelion/server/lib/build_target.js @@ -1,16 +1,16 @@ -let moment = require('moment'); +const moment = require('moment'); -let splitInterval = require('./split_interval.js'); +const splitInterval = require('./split_interval.js'); module.exports = function (tlConfig) { - let min = moment(tlConfig.time.from); - let max = moment(tlConfig.time.to); + const min = moment(tlConfig.time.from); + const max = moment(tlConfig.time.to); - let intervalParts = splitInterval(tlConfig.time.interval); + const intervalParts = splitInterval(tlConfig.time.interval); let current = min.startOf(intervalParts.unit); - let targetSeries = []; + const targetSeries = []; while (current.valueOf() < max.valueOf()) { targetSeries.push(current.valueOf()); diff --git a/src/core_plugins/timelion/server/lib/classes/chainable.js b/src/core_plugins/timelion/server/lib/classes/chainable.js index 7b8c7fe136168..4446a85251ead 100644 --- a/src/core_plugins/timelion/server/lib/classes/chainable.js +++ b/src/core_plugins/timelion/server/lib/classes/chainable.js @@ -1,4 +1,4 @@ -let TimelionFunction = require('./timelion_function'); +const TimelionFunction = require('./timelion_function'); module.exports = class Chainable extends TimelionFunction { constructor(name, config) { diff --git a/src/core_plugins/timelion/server/lib/classes/datasource.js b/src/core_plugins/timelion/server/lib/classes/datasource.js index 8b64e9eb58c64..ef7884cc8a366 100644 --- a/src/core_plugins/timelion/server/lib/classes/datasource.js +++ b/src/core_plugins/timelion/server/lib/classes/datasource.js @@ -1,10 +1,10 @@ -let loadFunctions = require('../load_functions.js'); -let fitFunctions = loadFunctions('fit_functions'); -let TimelionFunction = require('./timelion_function'); -let offsetTime = require('../offset_time'); +const loadFunctions = require('../load_functions.js'); +const fitFunctions = loadFunctions('fit_functions'); +const TimelionFunction = require('./timelion_function'); +const offsetTime = require('../offset_time'); -let _ = require('lodash'); -let moment = require('moment'); +const _ = require('lodash'); +const moment = require('moment'); function offsetSeries(response, offset) { @@ -33,9 +33,9 @@ module.exports = class Datasource extends TimelionFunction { }); // Wrap the original function so we can modify inputs/outputs with offset & fit - let originalFunction = config.fn; + const originalFunction = config.fn; config.fn = function (args, tlConfig) { - let config = _.clone(tlConfig); + const config = _.clone(tlConfig); if (args.byName.offset) { config.time = _.cloneDeep(tlConfig.time); config.time.from = offsetTime(config.time.from, args.byName.offset); diff --git a/src/core_plugins/timelion/server/lib/classes/timelion_function.js b/src/core_plugins/timelion/server/lib/classes/timelion_function.js index 96dc49c619b7a..8d804a4bdf460 100644 --- a/src/core_plugins/timelion/server/lib/classes/timelion_function.js +++ b/src/core_plugins/timelion/server/lib/classes/timelion_function.js @@ -1,6 +1,6 @@ -let _ = require('lodash'); -let loadFunctions = require('../load_functions.js'); -let fitFunctions = loadFunctions('fit_functions'); +const _ = require('lodash'); +const loadFunctions = require('../load_functions.js'); +const fitFunctions = loadFunctions('fit_functions'); module.exports = class TimelionFunction { constructor(name, config) { @@ -12,16 +12,16 @@ module.exports = class TimelionFunction { this.extended = config.extended || false; // WTF is this? How could you not have a fn? Wtf would the thing be used for? - let originalFunction = config.fn || function (input) { return input; }; + const originalFunction = config.fn || function (input) { return input; }; // Currently only re-fits the series. this.originalFn = originalFunction; this.fn = function (args, tlConfig) { - let config = _.clone(tlConfig); + const config = _.clone(tlConfig); return Promise.resolve(originalFunction(args, config)).then(function (seriesList) { seriesList.list = _.map(seriesList.list, function (series) { - let target = tlConfig.getTargetSeries(); + const target = tlConfig.getTargetSeries(); // Don't fit if the series are already the same if (_.isEqual(_.map(series.data, 0), _.map(target, 0))) return series; diff --git a/src/core_plugins/timelion/server/lib/date_math.js b/src/core_plugins/timelion/server/lib/date_math.js index 6ae0f998e5eca..ec9546853c670 100644 --- a/src/core_plugins/timelion/server/lib/date_math.js +++ b/src/core_plugins/timelion/server/lib/date_math.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); -let moment = require('moment'); +const _ = require('lodash'); +const moment = require('moment'); -let units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; +const units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; /* This is a simplified version of elasticsearch's date parser */ function parse(text, roundUp) { @@ -44,10 +44,10 @@ function parse(text, roundUp) { } function parseDateMath(mathString, time, roundUp) { - let dateTime = time; + const dateTime = time; for (let i = 0; i < mathString.length;) { - let c = mathString.charAt(i++); + const c = mathString.charAt(i++); let type; let num; let unit; @@ -67,7 +67,7 @@ function parseDateMath(mathString, time, roundUp) { } else if (mathString.length === 2) { num = mathString.charAt(i); } else { - let numFrom = i; + const numFrom = i; while (!isNaN(mathString.charAt(i))) { i++; if (i > 10) { diff --git a/src/core_plugins/timelion/server/lib/functions_md.js b/src/core_plugins/timelion/server/lib/functions_md.js index 93056c13199fc..94fab452eea09 100644 --- a/src/core_plugins/timelion/server/lib/functions_md.js +++ b/src/core_plugins/timelion/server/lib/functions_md.js @@ -1,10 +1,10 @@ -let loadFunctions = require('./load_functions.js'); -let functions = loadFunctions('series_functions/'); -let _ = require('lodash'); +const loadFunctions = require('./load_functions.js'); +const functions = loadFunctions('series_functions/'); +const _ = require('lodash'); module.exports = (function () { - let functionArray = _.map(functions, function (val, key) { + const functionArray = _.map(functions, function (val, key) { // TODO: This won't work on frozen objects, it should be removed when everything is converted to datasources and chainables return _.extend({}, val, {name: key}); }); @@ -18,7 +18,7 @@ module.exports = (function () { help += fn.help + '\n\n'; // If chainable, drop first argument from help - let args = fn.chainable ? fn.args.slice(1) : fn.args.slice(); + const args = fn.chainable ? fn.args.slice(1) : fn.args.slice(); if (!args.length) { help += '*This function does not accept any arguments.*\n\n'; return help; diff --git a/src/core_plugins/timelion/server/lib/get_namespaced_settings.js b/src/core_plugins/timelion/server/lib/get_namespaced_settings.js index dd10ac30c456e..4222f6732d9eb 100644 --- a/src/core_plugins/timelion/server/lib/get_namespaced_settings.js +++ b/src/core_plugins/timelion/server/lib/get_namespaced_settings.js @@ -1,10 +1,10 @@ -let _ = require('lodash'); -let configFile = require('../../timelion.json'); +const _ = require('lodash'); +const configFile = require('../../timelion.json'); module.exports = function () { function flattenWith(dot, nestedObj, flattenArrays) { - let stack = []; // track key stack - let flatObj = {}; + const stack = []; // track key stack + const flatObj = {}; (function flattenObj(obj) { _.keys(obj).forEach(function (key) { stack.push(key); @@ -17,7 +17,7 @@ module.exports = function () { return flatObj; }; - let timelionDefaults = flattenWith('.', configFile); + const timelionDefaults = flattenWith('.', configFile); return _.reduce(timelionDefaults, (result, value, key) => { result['timelion:' + key] = value; return result; diff --git a/src/core_plugins/timelion/server/lib/load_functions.js b/src/core_plugins/timelion/server/lib/load_functions.js index bb9e905c75b99..9bcfbef7b6101 100644 --- a/src/core_plugins/timelion/server/lib/load_functions.js +++ b/src/core_plugins/timelion/server/lib/load_functions.js @@ -1,33 +1,33 @@ -let _ = require('lodash'); -let glob = require('glob'); -let path = require('path'); -let processFunctionDefinition = require('./process_function_definition'); +const _ = require('lodash'); +const glob = require('glob'); +const path = require('path'); +const processFunctionDefinition = require('./process_function_definition'); module.exports = function (directory) { function getTuple(directory, name) { - let func = require('../' + directory + '/' + name); + const func = require('../' + directory + '/' + name); return [name, require('../' + directory + '/' + name)]; } // Get a list of all files and use the filename as the object key - let files = _.map(glob.sync(path.resolve(__dirname, '../' + directory + '/*.js')), function (file) { - let name = file.substring(file.lastIndexOf('/') + 1, file.lastIndexOf('.')); + const files = _.map(glob.sync(path.resolve(__dirname, '../' + directory + '/*.js')), function (file) { + const name = file.substring(file.lastIndexOf('/') + 1, file.lastIndexOf('.')); return getTuple(directory, name); }); // Get a list of all directories with an index.js, use the directory name as the key in the object - let directories = _.chain(glob.sync(path.resolve(__dirname, '../' + directory + '/*/index.js'))) + const directories = _.chain(glob.sync(path.resolve(__dirname, '../' + directory + '/*/index.js'))) .filter(function (file) { return file.match(/__test__/) == null; }) .map(function (file) { - let parts = file.split('/'); - let name = parts[parts.length - 2]; + const parts = file.split('/'); + const name = parts[parts.length - 2]; return getTuple(directory, parts[parts.length - 2]); }).value(); - let functions = _.zipObject(files.concat(directories)); + const functions = _.zipObject(files.concat(directories)); _.each(functions, function (func) { _.assign(functions, processFunctionDefinition(func)); diff --git a/src/core_plugins/timelion/server/lib/offset_time.js b/src/core_plugins/timelion/server/lib/offset_time.js index c22d824acc88f..ab2059005f02c 100644 --- a/src/core_plugins/timelion/server/lib/offset_time.js +++ b/src/core_plugins/timelion/server/lib/offset_time.js @@ -1,17 +1,17 @@ -let moment = require('moment'); +const moment = require('moment'); // usually reverse = false on the request, true on the response module.exports = function offsetTime(milliseconds, offset, reverse) { if (!offset.match(/[-+][0-9]+[mshdwMy]/g)) { throw new Error ('Malformed `offset` at ' + offset); } - let parts = offset.match(/[-+]|[0-9]+|[mshdwMy]/g); + const parts = offset.match(/[-+]|[0-9]+|[mshdwMy]/g); let add = parts[0] === '+'; add = reverse ? !add : add; - let mode = add ? 'add' : 'subtract'; + const mode = add ? 'add' : 'subtract'; - let momentObj = moment(milliseconds)[mode](parts[1], parts[2]); + const momentObj = moment(milliseconds)[mode](parts[1], parts[2]); return momentObj.valueOf(); }; diff --git a/src/core_plugins/timelion/server/lib/process_function_definition.js b/src/core_plugins/timelion/server/lib/process_function_definition.js index 8afe0ab276d10..d6bec2e79db04 100644 --- a/src/core_plugins/timelion/server/lib/process_function_definition.js +++ b/src/core_plugins/timelion/server/lib/process_function_definition.js @@ -1,11 +1,11 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function (func) { - let functions = {}; + const functions = {}; functions[func.name] = func; if (func.aliases) { _.each(func.aliases, function (alias) { - let aliasFn = _.clone(func); + const aliasFn = _.clone(func); aliasFn.isAlias = true; functions[alias] = aliasFn; }); diff --git a/src/core_plugins/timelion/server/lib/reduce.js b/src/core_plugins/timelion/server/lib/reduce.js index 53971f2a11720..a97b24b987414 100644 --- a/src/core_plugins/timelion/server/lib/reduce.js +++ b/src/core_plugins/timelion/server/lib/reduce.js @@ -1,5 +1,5 @@ -let _ = require('lodash'); -let Promise = require('bluebird'); +const _ = require('lodash'); +const Promise = require('bluebird'); /** @@ -15,7 +15,7 @@ let Promise = require('bluebird'); module.exports = function reduce(args, fn) { return Promise.all(args).then(function (args) { - let seriesList = args.shift(); + const seriesList = args.shift(); let argument = args.shift(); if (seriesList.type !== 'seriesList') { @@ -36,7 +36,7 @@ module.exports = function reduce(args, fn) { let output = _.map(destinationObject.data, function (point, index) { - let value = point[1]; + const value = point[1]; if (value == null) { return [point[0], null]; diff --git a/src/core_plugins/timelion/server/lib/split_interval.js b/src/core_plugins/timelion/server/lib/split_interval.js index 11ad0f9239b30..db7ae68811dc8 100644 --- a/src/core_plugins/timelion/server/lib/split_interval.js +++ b/src/core_plugins/timelion/server/lib/split_interval.js @@ -2,7 +2,7 @@ module.exports = function splitInterval(interval) { if (!interval.match(/[0-9]+[mshdwMy]+/g)) { throw new Error ('Malformed `interval`: ' + interval); } - let parts = interval.match(/[0-9]+|[mshdwMy]+/g); + const parts = interval.match(/[0-9]+|[mshdwMy]+/g); return { count: parts[0], diff --git a/src/core_plugins/timelion/server/lib/to_milliseconds.js b/src/core_plugins/timelion/server/lib/to_milliseconds.js index 17318017fd8fb..83aebc41278d7 100644 --- a/src/core_plugins/timelion/server/lib/to_milliseconds.js +++ b/src/core_plugins/timelion/server/lib/to_milliseconds.js @@ -1,9 +1,9 @@ -let _ = require('lodash'); -let moment = require('moment'); +const _ = require('lodash'); +const moment = require('moment'); // map of moment's short/long unit ids and elasticsearch's long unit ids // to their value in milliseconds -let vals = _.transform([ +const vals = _.transform([ ['ms', 'milliseconds', 'millisecond'], ['s', 'seconds', 'second', 'sec'], ['m', 'minutes', 'minute', 'min'], @@ -14,17 +14,17 @@ let vals = _.transform([ ['quarter'], ['y', 'years', 'year'] ], function (vals, units) { - let normal = moment.normalizeUnits(units[0]); - let val = moment.duration(1, normal).asMilliseconds(); + const normal = moment.normalizeUnits(units[0]); + const val = moment.duration(1, normal).asMilliseconds(); [].concat(normal, units).forEach(function (unit) { vals[unit] = val; }); }, {}); // match any key from the vals object prececed by an optional number -let parseRE = new RegExp('^(\\d+(?:\\.\\d*)?)?\\s*(' + _.keys(vals).join('|') + ')$'); +const parseRE = new RegExp('^(\\d+(?:\\.\\d*)?)?\\s*(' + _.keys(vals).join('|') + ')$'); module.exports = function (expr) { - let match = expr.match(parseRE); + const match = expr.match(parseRE); if (match) { if (match[2] === 'M' && match[1] !== '1') { throw new Error ('Invalid interval. 1M is only valid monthly interval.'); diff --git a/src/core_plugins/timelion/server/lib/unzipPairs.js b/src/core_plugins/timelion/server/lib/unzipPairs.js index 71b4ddefb3aa9..c673ad855ea73 100644 --- a/src/core_plugins/timelion/server/lib/unzipPairs.js +++ b/src/core_plugins/timelion/server/lib/unzipPairs.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function unzipPairs(timeValObject) { - let paired = _.chain(timeValObject).pairs().map(function (point) { + const paired = _.chain(timeValObject).pairs().map(function (point) { return [parseInt(point[0], 10), point[1]]; }).sortBy(function (point) { return point[0]; diff --git a/src/core_plugins/timelion/server/routes/functions.js b/src/core_plugins/timelion/server/routes/functions.js index 60227ecd79147..b3363c4d6c71e 100644 --- a/src/core_plugins/timelion/server/routes/functions.js +++ b/src/core_plugins/timelion/server/routes/functions.js @@ -1,11 +1,11 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function (server) { server.route({ method: 'GET', path: '/api/timelion/functions', handler: function (request, reply) { - let functionArray = _.map(server.plugins.timelion.functions, function (val, key) { + const functionArray = _.map(server.plugins.timelion.functions, function (val, key) { // TODO: This won't work on frozen objects, it should be removed when everything is converted to datasources and chainables return _.extend({}, val, {name: key}); }); diff --git a/src/core_plugins/timelion/server/routes/run.js b/src/core_plugins/timelion/server/routes/run.js index e6192de69de89..753b94dd55bca 100644 --- a/src/core_plugins/timelion/server/routes/run.js +++ b/src/core_plugins/timelion/server/routes/run.js @@ -1,8 +1,8 @@ -let Promise = require('bluebird'); -let _ = require('lodash'); -let Boom = require('boom'); -let chainRunnerFn = require('../handlers/chain_runner.js'); -let timelionDefaults = require('../lib/get_namespaced_settings')(); +const Promise = require('bluebird'); +const _ = require('lodash'); +const Boom = require('boom'); +const chainRunnerFn = require('../handlers/chain_runner.js'); +const timelionDefaults = require('../lib/get_namespaced_settings')(); function replyWithError(e, reply) { reply({title: e.toString(), message: e.toString(), stack: e.stack}).code(400); @@ -21,12 +21,12 @@ module.exports = (server) => { // down. Meh. return server.uiSettings().getAll().then((uiSettings) => { let sheet; - let tlConfig = require('../handlers/lib/tl_config.js')({ + const tlConfig = require('../handlers/lib/tl_config.js')({ server: server, request: request, settings: _.defaults(uiSettings, timelionDefaults) // Just in case they delete some setting. }); - let chainRunner = chainRunnerFn(tlConfig); + const chainRunner = chainRunnerFn(tlConfig); try { sheet = chainRunner.processRequest(request.payload || { @@ -44,7 +44,7 @@ module.exports = (server) => { } return Promise.all(sheet).then((sheet) => { - let response = { + const response = { sheet: sheet, stats: chainRunner.getStats() }; diff --git a/src/core_plugins/timelion/server/routes/validate_es.js b/src/core_plugins/timelion/server/routes/validate_es.js index 4fab86a251257..1796e2449a02e 100644 --- a/src/core_plugins/timelion/server/routes/validate_es.js +++ b/src/core_plugins/timelion/server/routes/validate_es.js @@ -5,11 +5,11 @@ module.exports = function (server) { handler: function (request, reply) { return server.uiSettings().getAll().then((uiSettings) => { - let callWithRequest = server.plugins.elasticsearch.callWithRequest; + const callWithRequest = server.plugins.elasticsearch.callWithRequest; - let timefield = uiSettings['timelion:es.timefield']; + const timefield = uiSettings['timelion:es.timefield']; - let body = { + const body = { index: uiSettings['es.default_index'], fields:timefield }; diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/abs.js b/src/core_plugins/timelion/server/series_functions/__tests__/abs.js index a13676b49abd8..4fe8f6e65eb4d 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/abs.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/abs.js @@ -1,20 +1,20 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); -let _ = require('lodash'); -let expect = require('chai').expect; -let seriesList = require('./fixtures/seriesList.js')(); -let invoke = require('./helpers/invoke_series_fn.js'); +const _ = require('lodash'); +const expect = require('chai').expect; +const seriesList = require('./fixtures/seriesList.js')(); +const invoke = require('./helpers/invoke_series_fn.js'); describe(filename, function () { it('should return the positive value of every value', function () { return invoke(fn, [seriesList]).then(function (result) { - let before = _.filter(result.input[0].list[0].data, function (point) { + const before = _.filter(result.input[0].list[0].data, function (point) { return (point[1] < 0); }); - let after = _.filter(result.output.list[0].data, function (point) { + const after = _.filter(result.output.list[0].data, function (point) { return (point[1] < 0); }); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/bars.js b/src/core_plugins/timelion/server/series_functions/__tests__/bars.js index ea6c79cae8d22..c4f086dcac238 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/bars.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/bars.js @@ -1,9 +1,9 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); -let _ = require('lodash'); -let expect = require('chai').expect; -let invoke = require('./helpers/invoke_series_fn.js'); +const _ = require('lodash'); +const expect = require('chai').expect; +const invoke = require('./helpers/invoke_series_fn.js'); describe(filename, () => { @@ -14,7 +14,7 @@ describe(filename, () => { it('creates the bars property, with defaults, on all series', () => { return invoke(fn, [seriesList]).then((r) => { - let bars = _.map(r.output.list, 'bars'); + const bars = _.map(r.output.list, 'bars'); _.each(bars, (bar) => expect(bar).to.be.a('object')); _.each(bars, (bar) => expect(bar.lineWidth).to.equal(6)); _.each(bars, (bar) => expect(bar.show).to.equal(1)); @@ -24,7 +24,7 @@ describe(filename, () => { it('leaves existing bars alone when called without option, if they exist', () => { seriesList.list[0].bars = {foo: true}; return invoke(fn, [seriesList]).then((r) => { - let bars = _.map(r.output.list, 'bars'); + const bars = _.map(r.output.list, 'bars'); expect(bars[0].foo).to.equal(true); expect(bars[1].foo).to.equal(undefined); }); @@ -32,7 +32,7 @@ describe(filename, () => { it('sets lineWidth and show to the same value', () => { return invoke(fn, [seriesList, 0]).then((r) => { - let bars = _.map(r.output.list, 'bars'); + const bars = _.map(r.output.list, 'bars'); expect(bars[0].lineWidth).to.equal(0); expect(bars[0].show).to.equal(0); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/condition.js b/src/core_plugins/timelion/server/series_functions/__tests__/condition.js index 6df056d23e4f0..18db74555b777 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/condition.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/condition.js @@ -1,10 +1,10 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); -let moment = require('moment'); -let expect = require('chai').expect; -let invoke = require('./helpers/invoke_series_fn.js'); -let getSeriesList = require('./helpers/get_single_series_list'); -let _ = require('lodash'); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); +const moment = require('moment'); +const expect = require('chai').expect; +const invoke = require('./helpers/invoke_series_fn.js'); +const getSeriesList = require('./helpers/get_single_series_list'); +const _ = require('lodash'); describe(filename, function () { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/es.js b/src/core_plugins/timelion/server/series_functions/__tests__/es.js index e2ea4d9cb20dd..9fcec994a3675 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/es.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/es.js @@ -166,16 +166,16 @@ describe(filename, () => { it('adds the contents of payload.extended.es.filter to a filter clause of the bool', () => { config.kibana = true; - let request = fn(config, tlConfig); - let filter = request.body.query.bool.filter.bool; + const request = fn(config, tlConfig); + const filter = request.body.query.bool.filter.bool; expect(filter.must.length).to.eql(1); expect(filter.must_not.length).to.eql(2); }); it('does not include filters if config.kibana = false', () => { config.kibana = false; - let request = fn(config, tlConfig); - let filter = request.body.query.bool.filter; + const request = fn(config, tlConfig); + const filter = request.body.query.bool.filter; expect(request.body.query.bool.filter).to.eql(undefined); }); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/first.js b/src/core_plugins/timelion/server/series_functions/__tests__/first.js index 67c40cda8bab4..d08b8b0ad9627 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/first.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/first.js @@ -1,9 +1,9 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); -let expect = require('chai').expect; -let seriesList = require('./fixtures/seriesList.js')(); -let invoke = require('./helpers/invoke_series_fn.js'); +const expect = require('chai').expect; +const seriesList = require('./fixtures/seriesList.js')(); +const invoke = require('./helpers/invoke_series_fn.js'); describe(filename, function () { it('should return exactly the data input', function () { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fit.js b/src/core_plugins/timelion/server/series_functions/__tests__/fit.js index c181f8c53355d..27b4a5200e690 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fit.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fit.js @@ -1,16 +1,16 @@ -let filename = require('path').basename(__filename); -let fn = require(`../${filename}`); -let moment = require('moment'); -let expect = require('chai').expect; -let invoke = require('./helpers/invoke_series_fn.js'); -let getSeriesList = require('./helpers/get_single_series_list'); -let _ = require('lodash'); +const filename = require('path').basename(__filename); +const fn = require(`../${filename}`); +const moment = require('moment'); +const expect = require('chai').expect; +const invoke = require('./helpers/invoke_series_fn.js'); +const getSeriesList = require('./helpers/get_single_series_list'); +const _ = require('lodash'); describe(filename, function () { describe('carry', function () { it('should maintain the previous value until it changes', function () { - let seriesList = getSeriesList('',[ + const seriesList = getSeriesList('',[ [moment.utc('1980-01-01T00:00:00.000Z'), 5], [moment.utc('1981-01-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), 3.4], @@ -27,7 +27,7 @@ describe(filename, function () { describe('nearest', function () { it('should use the closest temporal value to fill the null', function () { - let seriesList = getSeriesList('',[ + const seriesList = getSeriesList('',[ [moment.utc('1980-01-01T00:00:00.000Z'), 5], [moment.utc('1981-01-01T00:00:00.000Z'), null], [moment.utc('1981-05-01T00:00:00.000Z'), 3.4], @@ -46,7 +46,7 @@ describe(filename, function () { describe('average', function () { it('should produce a smooth, straight line between points', function () { - let seriesList = getSeriesList('',[ + const seriesList = getSeriesList('',[ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), null], @@ -64,7 +64,7 @@ describe(filename, function () { describe('scale', function () { it('should distribute the next points value across the preceeding nulls', function () { - let seriesList = getSeriesList('', [ + const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), null], @@ -80,7 +80,7 @@ describe(filename, function () { describe('none', function () { it('basically just drops the nulls. This is going to screw you', function () { - let seriesList = getSeriesList('', [ + const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], [moment.utc('1982-01-01T00:00:00.000Z'), null], diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js index 37c08ebfe2d82..45ac73ee3bd72 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/bucketList.js @@ -1,4 +1,4 @@ -let moment = require('moment'); +const moment = require('moment'); module.exports = [ moment('1980-01-01T00:00:00.000Z'), diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js index 0f814c98aeb62..e52710a33f5dc 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/seriesList.js @@ -1,8 +1,8 @@ -let Promise = require('bluebird'); -let buckets = require('./bucketList'); -let getSeries = require('../helpers/get_series'); -let getSeriesList = require('../helpers/get_series_list'); -let _ = require('lodash'); +const Promise = require('bluebird'); +const buckets = require('./bucketList'); +const getSeries = require('../helpers/get_series'); +const getSeriesList = require('../helpers/get_series_list'); +const _ = require('lodash'); module.exports = function () { return getSeriesList([ diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js index e83b25b051ddc..7d159e7898a51 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/fixtures/tlConfig.js @@ -1,8 +1,8 @@ -let moment = require('moment'); -let timelionDefaults = require('../../../lib/get_namespaced_settings'); +const moment = require('moment'); +const timelionDefaults = require('../../../lib/get_namespaced_settings'); module.exports = function () { - let tlConfig = require('../../../handlers/lib/tl_config.js')({ + const tlConfig = require('../../../handlers/lib/tl_config.js')({ server: {}, request: {} }); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js b/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js index 55df757305334..c1c0b8a11386f 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/graphite.js @@ -1,9 +1,9 @@ -let proxyquire = require('proxyquire'); -let Promise = require('bluebird'); -let _ = require('lodash'); -let expect = require('chai').expect; +const proxyquire = require('proxyquire'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const expect = require('chai').expect; -let graphiteResponse = function (url) { +const graphiteResponse = function (url) { return Promise.resolve({ json: function () { return [{ @@ -19,10 +19,10 @@ let graphiteResponse = function (url) { }); }; -let filename = require('path').basename(__filename); -let fn = proxyquire(`../${filename}`, {'node-fetch': graphiteResponse}); +const filename = require('path').basename(__filename); +const fn = proxyquire(`../${filename}`, {'node-fetch': graphiteResponse}); -let invoke = require('./helpers/invoke_series_fn.js'); +const invoke = require('./helpers/invoke_series_fn.js'); describe(filename, function () { it('should wrap the graphite response up in a seriesList', function () { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js index 3cb52252e7bfe..0eaa42967e4e5 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function getSeries(name, buckets, points) { - let fill = _.partial(_.zip, _.map(buckets, function (bucket) { return bucket.valueOf(); })); + const fill = _.partial(_.zip, _.map(buckets, function (bucket) { return bucket.valueOf(); })); return { data: fill(points), type: 'series', diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js index 439886963e62e..26dcdadf518a1 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_series_list.js @@ -1,4 +1,4 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function (list, overrides) { return _.merge({ diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js index 5ace294cc16b3..88ee01b18cd69 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/get_single_series_list.js @@ -1,6 +1,6 @@ -let getSeries = require('../helpers/get_series'); -let getSeriesList = require('../helpers/get_series_list'); -let _ = require('lodash'); +const getSeries = require('../helpers/get_series'); +const getSeriesList = require('../helpers/get_series_list'); +const _ = require('lodash'); module.exports = function (name, data) { return getSeriesList([getSeries(name, _.map(data, 0), _.map(data, 1))]); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js index 573b2df62d5aa..b53bffd8026cb 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/helpers/invoke_series_fn.js @@ -1,18 +1,18 @@ // invokes a series_function with the specified arguments -let _ = require('lodash'); -let indexArguments = require('../../../handlers/lib/index_arguments'); +const _ = require('lodash'); +const indexArguments = require('../../../handlers/lib/index_arguments'); module.exports = function invokeSeriesFn(fnDef, args, tlConfigOverrides) { - let tlConfig = _.merge(require('../fixtures/tlConfig')(), tlConfigOverrides); + const tlConfig = _.merge(require('../fixtures/tlConfig')(), tlConfigOverrides); return Promise.all(args).then(function (args) { args.byName = indexArguments(fnDef, args); - let input = _.cloneDeep(args); + const input = _.cloneDeep(args); return Promise.resolve(fnDef.originalFn(args, tlConfig)).then(function (output) { - let result = { + const result = { output: output, input: input }; diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js b/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js index 345b50331074b..2a611ced249a0 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/movingstd.js @@ -14,7 +14,7 @@ describe(filename, () => { it('computes the moving standard deviation of a list', () => { return invoke(fn, [seriesList, 2]).then((r) => { - let values = _.map(r.output.list[1].data, 1); + const values = _.map(r.output.list[1].data, 1); expect(values[0]).to.equal(null); expect(values[1]).to.equal(null); expect(values[2]).to.be.within(26, 27); diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/points.js b/src/core_plugins/timelion/server/series_functions/__tests__/points.js index 3918d752bc13f..eff783b6204d3 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/points.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/points.js @@ -44,7 +44,7 @@ describe(filename, () => { }); describe('symbol', () => { - let symbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; + const symbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; _.each(symbols, (symbol) => { it(`is ${symbol}`, () => { return invoke(fn, [seriesList, null, null, null, null, symbol]).then((r) => { diff --git a/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js b/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js index 9e01408c1c423..172786f411e5d 100644 --- a/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js +++ b/src/core_plugins/timelion/server/series_functions/__tests__/quandl.js @@ -1,16 +1,16 @@ -let proxyquire = require('proxyquire'); -let Promise = require('bluebird'); -let _ = require('lodash'); +const proxyquire = require('proxyquire'); +const Promise = require('bluebird'); +const _ = require('lodash'); const assert = require('chai'); const expect = assert.expect; -let parseURL = require('url').parse; -let parseQueryString = require('querystring').parse; -let tlConfig = require('./fixtures/tlConfig')(); -let moment = require('moment'); +const parseURL = require('url').parse; +const parseQueryString = require('querystring').parse; +const tlConfig = require('./fixtures/tlConfig')(); +const moment = require('moment'); -let filename = require('path').basename(__filename); -let invoke = require('./helpers/invoke_series_fn.js'); +const filename = require('path').basename(__filename); +const invoke = require('./helpers/invoke_series_fn.js'); let fn; let response; diff --git a/src/core_plugins/timelion/server/series_functions/abs.js b/src/core_plugins/timelion/server/series_functions/abs.js index 6f1ac19665028..7e505da67bec6 100644 --- a/src/core_plugins/timelion/server/series_functions/abs.js +++ b/src/core_plugins/timelion/server/series_functions/abs.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('abs', { args: [ { @@ -11,7 +11,7 @@ module.exports = new Chainable('abs', { help: 'Return the absolute value of each value in the series list', fn: function absFn(args) { return alter(args, function (eachSeries) { - let data = _.map(eachSeries.data, function (point) { + const data = _.map(eachSeries.data, function (point) { return [point[0], Math.abs(point[1])]; }); eachSeries.data = data; diff --git a/src/core_plugins/timelion/server/series_functions/bars.js b/src/core_plugins/timelion/server/series_functions/bars.js index 3a1ed374ac614..70284d7ce03d8 100644 --- a/src/core_plugins/timelion/server/series_functions/bars.js +++ b/src/core_plugins/timelion/server/series_functions/bars.js @@ -1,5 +1,5 @@ -let alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('bars', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/color.js b/src/core_plugins/timelion/server/series_functions/color.js index 39318c78ef753..329f02971ba81 100644 --- a/src/core_plugins/timelion/server/series_functions/color.js +++ b/src/core_plugins/timelion/server/series_functions/color.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); -let tinygradient = require('tinygradient'); +const alter = require('../lib/alter.js'); +const Chainable = require('../lib/classes/chainable'); +const tinygradient = require('tinygradient'); module.exports = new Chainable('color', { args: [ diff --git a/src/core_plugins/timelion/server/series_functions/condition.js b/src/core_plugins/timelion/server/series_functions/condition.js index 64323e89a8fdf..b30f20298a3fe 100644 --- a/src/core_plugins/timelion/server/series_functions/condition.js +++ b/src/core_plugins/timelion/server/series_functions/condition.js @@ -1,7 +1,7 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); -let argType = require('../handlers/lib/arg_type.js'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); +const argType = require('../handlers/lib/arg_type.js'); module.exports = new Chainable('condition', { args: [ @@ -35,9 +35,9 @@ module.exports = new Chainable('condition', { 'to the result if the condition proves true, with an optional else.', aliases: ['if'], fn: function conditionFn(args) { - let config = args.byName; + const config = args.byName; return alter(args, function (eachSeries) { - let data = _.map(eachSeries.data, function (point, i) { + const data = _.map(eachSeries.data, function (point, i) { function getNumber(source) { if (argType(source) === 'number') return source; if (argType(source) === 'null') return null; @@ -45,11 +45,11 @@ module.exports = new Chainable('condition', { throw new Error ('must be a number or a seriesList'); } - let ifVal = getNumber(config.if); - let thenVal = getNumber(config.then); - let elseVal = _.isUndefined(config.else) ? point[1] : getNumber(config.else); + const ifVal = getNumber(config.if); + const thenVal = getNumber(config.then); + const elseVal = _.isUndefined(config.else) ? point[1] : getNumber(config.else); - let newValue = (function () { + const newValue = (function () { switch (config.operator) { case 'lt': return point[1] < ifVal ? thenVal : elseVal; diff --git a/src/core_plugins/timelion/server/series_functions/cusum.js b/src/core_plugins/timelion/server/series_functions/cusum.js index 058f0545c6cf3..4f7023d96a850 100644 --- a/src/core_plugins/timelion/server/series_functions/cusum.js +++ b/src/core_plugins/timelion/server/series_functions/cusum.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('cusum', { args: [ { @@ -16,7 +16,7 @@ module.exports = new Chainable('cusum', { help: 'Return the cumulative sum of a series, starting at a base.', fn: function cusumFn(args) { return alter(args, function (eachSeries, base) { - let pairs = eachSeries.data; + const pairs = eachSeries.data; let total = base || 0; eachSeries.data = _.map(pairs, function (point, i) { total += point[1]; diff --git a/src/core_plugins/timelion/server/series_functions/derivative.js b/src/core_plugins/timelion/server/series_functions/derivative.js index 0417112966f7d..9ace58139ede7 100644 --- a/src/core_plugins/timelion/server/series_functions/derivative.js +++ b/src/core_plugins/timelion/server/series_functions/derivative.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('derivative', { args: [ { @@ -11,7 +11,7 @@ module.exports = new Chainable('derivative', { help: 'Plot the change in values over time.', fn: function derivativeFn(args) { return alter(args, function (eachSeries) { - let pairs = eachSeries.data; + const pairs = eachSeries.data; eachSeries.data = _.map(pairs, function (point, i) { if (i === 0 || pairs[i - 1][1] == null || point[1] == null) { return [point[0], null]; } return [point[0], point[1] - pairs[i - 1][1]]; diff --git a/src/core_plugins/timelion/server/series_functions/divide.js b/src/core_plugins/timelion/server/series_functions/divide.js index ef6c78fb751b8..c0828deebc7f1 100644 --- a/src/core_plugins/timelion/server/series_functions/divide.js +++ b/src/core_plugins/timelion/server/series_functions/divide.js @@ -1,6 +1,6 @@ -let reduce = require('../lib/reduce.js'); +const reduce = require('../lib/reduce.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('divide', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/es/index.js b/src/core_plugins/timelion/server/series_functions/es/index.js index 7d63f564733b4..b0bf4811a9b4e 100644 --- a/src/core_plugins/timelion/server/series_functions/es/index.js +++ b/src/core_plugins/timelion/server/series_functions/es/index.js @@ -1,8 +1,8 @@ -let _ = require('lodash'); -let moment = require('moment'); -let toMS = require('../../lib/to_milliseconds.js'); -let Datasource = require('../../lib/classes/datasource'); -let buildRequest = require('./lib/build_request'); +const _ = require('lodash'); +const moment = require('moment'); +const toMS = require('../../lib/to_milliseconds.js'); +const Datasource = require('../../lib/classes/datasource'); +const buildRequest = require('./lib/build_request'); import toSeriesList from './lib/agg_response_to_series_list'; module.exports = new Datasource('es', { @@ -51,7 +51,7 @@ module.exports = new Datasource('es', { aliases: ['elasticsearch'], fn: function esFn(args, tlConfig) { - let config = _.defaults(_.clone(args.byName), { + const config = _.defaults(_.clone(args.byName), { q: '*', metric: ['count'], index: tlConfig.settings['timelion:es.default_index'], @@ -61,9 +61,9 @@ module.exports = new Datasource('es', { fit: 'nearest' }); - let callWithRequest = tlConfig.server.plugins.elasticsearch.callWithRequest; + const callWithRequest = tlConfig.server.plugins.elasticsearch.callWithRequest; - let body = buildRequest(config, tlConfig); + const body = buildRequest(config, tlConfig); return callWithRequest(tlConfig.request, 'search', body).then(function (resp) { if (!resp._shards.total) throw new Error('Elasticsearch index not found: ' + config.index); return { diff --git a/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js b/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js index 47b920fb54a54..538983468e7b1 100644 --- a/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js +++ b/src/core_plugins/timelion/server/series_functions/es/lib/agg_response_to_series_list.js @@ -1,8 +1,8 @@ -let _ = require('lodash'); +const _ = require('lodash'); export function timeBucketsToPairs(buckets) { - let timestamps = _.pluck(buckets, 'key'); - let series = {}; + const timestamps = _.pluck(buckets, 'key'); + const series = {}; _.each(buckets, function (bucket) { _.forOwn(bucket, function (val, key) { if (_.isPlainObject(val)) { @@ -28,7 +28,7 @@ export function flattenBucket(bucket, path, result) { flattenBucket(bucket, path.concat([key + ':' + bucket.key]), result); }); } else if (_.get(val, 'meta.type') === 'time_buckets') { - let metrics = timeBucketsToPairs(val.buckets); + const metrics = timeBucketsToPairs(val.buckets); _.each(metrics, function (pairs, metricName) { result[path.concat([metricName]).join(' > ')] = pairs; }); diff --git a/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js b/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js index 21d0091028d24..e1ce9b6dc6c8a 100644 --- a/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js +++ b/src/core_plugins/timelion/server/series_functions/es/lib/build_request.js @@ -1,11 +1,11 @@ -let _ = require('lodash'); -let createDateAgg = require('./create_date_agg'); +const _ = require('lodash'); +const createDateAgg = require('./create_date_agg'); module.exports = function buildRequest(config, tlConfig) { - let bool = {must: [], must_not: []}; + const bool = {must: [], must_not: []}; - let timeFilter = {range:{}}; + const timeFilter = {range:{}}; timeFilter.range[config.timefield] = {gte: tlConfig.time.from, lte: tlConfig.time.to, format: 'epoch_millis'}; bool.must.push(timeFilter); @@ -14,7 +14,7 @@ module.exports = function buildRequest(config, tlConfig) { bool.filter = _.get(tlConfig, 'request.payload.extended.es.filter') || {}; } - let aggs = { + const aggs = { 'q': { meta: {type: 'split'}, filters: { diff --git a/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js b/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js index b448baa45ec1e..1b1b9072deeda 100644 --- a/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js +++ b/src/core_plugins/timelion/server/series_functions/es/lib/create_date_agg.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function createDateAgg(config, tlConfig) { - let dateAgg = { + const dateAgg = { time_buckets: { meta: {type: 'time_buckets'}, date_histogram: { @@ -30,7 +30,7 @@ module.exports = function createDateAgg(config, tlConfig) { } }; } else if (metric[0] && metric[1]) { - let metricName = metric[0] + '(' + metric[1] + ')'; + const metricName = metric[0] + '(' + metric[1] + ')'; dateAgg.time_buckets.aggs[metricName] = {}; dateAgg.time_buckets.aggs[metricName][metric[0]] = {field: metric[1]}; } else { diff --git a/src/core_plugins/timelion/server/series_functions/first.js b/src/core_plugins/timelion/server/series_functions/first.js index 5d82c1da22a82..b4d64a464ac7f 100644 --- a/src/core_plugins/timelion/server/series_functions/first.js +++ b/src/core_plugins/timelion/server/series_functions/first.js @@ -1,5 +1,5 @@ -let alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('first', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/fit.js b/src/core_plugins/timelion/server/series_functions/fit.js index f2b3afcb84cb1..d46148e31f815 100644 --- a/src/core_plugins/timelion/server/series_functions/fit.js +++ b/src/core_plugins/timelion/server/series_functions/fit.js @@ -1,9 +1,9 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); -let loadFunctions = require('../lib/load_functions.js'); -let fitFunctions = loadFunctions('fit_functions'); +const loadFunctions = require('../lib/load_functions.js'); +const fitFunctions = loadFunctions('fit_functions'); module.exports = new Chainable('fit', { args: [ @@ -21,7 +21,7 @@ module.exports = new Chainable('fit', { fn: function absFn(args) { return alter(args, function (eachSeries, mode) { - let noNulls = _.filter(eachSeries.data, 1); + const noNulls = _.filter(eachSeries.data, 1); eachSeries.data = fitFunctions[mode](noNulls, eachSeries.data); return eachSeries; diff --git a/src/core_plugins/timelion/server/series_functions/graphite.js b/src/core_plugins/timelion/server/series_functions/graphite.js index bb46ab20a57c2..2b95613949aa0 100644 --- a/src/core_plugins/timelion/server/series_functions/graphite.js +++ b/src/core_plugins/timelion/server/series_functions/graphite.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); -let fetch = require('node-fetch'); -let moment = require('moment'); -let Datasource = require('../lib/classes/datasource'); +const _ = require('lodash'); +const fetch = require('node-fetch'); +const moment = require('moment'); +const Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('graphite', { @@ -15,14 +15,14 @@ module.exports = new Datasource ('graphite', { help: `[experimental] Pull data from graphite. Configure your graphite server in Kibana's Advanced Settings`, fn: function graphite(args, tlConfig) { - let config = args.byName; + const config = args.byName; - let time = { + const time = { min: moment(tlConfig.time.from).format('HH:mm[_]YYYYMMDD'), max: moment(tlConfig.time.to).format('HH:mm[_]YYYYMMDD') }; - let URL = tlConfig.settings['timelion:graphite.url'] + '/render/' + + const URL = tlConfig.settings['timelion:graphite.url'] + '/render/' + '?format=json' + '&from=' + time.min + '&until=' + time.max + @@ -31,8 +31,8 @@ module.exports = new Datasource ('graphite', { return fetch(URL).then(function (resp) { return resp.json(); }).then(function (resp) { - let list = _.map(resp, function (series) { - let data = _.map(series.datapoints, function (point) { + const list = _.map(resp, function (series) { + const data = _.map(series.datapoints, function (point) { return [point[1] * 1000, point[0]]; }); return { diff --git a/src/core_plugins/timelion/server/series_functions/hide.js b/src/core_plugins/timelion/server/series_functions/hide.js index a49e550d6f499..6fc0a4435f674 100644 --- a/src/core_plugins/timelion/server/series_functions/hide.js +++ b/src/core_plugins/timelion/server/series_functions/hide.js @@ -1,5 +1,5 @@ -let alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('hide', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/holt/index.js b/src/core_plugins/timelion/server/series_functions/holt/index.js index 09405a4ea3a9a..9cc490fcc05bf 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/index.js +++ b/src/core_plugins/timelion/server/series_functions/holt/index.js @@ -1,9 +1,9 @@ -let _ = require('lodash'); -let Chainable = require('../../lib/classes/chainable'); -let ses = require('./lib/ses'); -let des = require('./lib/des'); -let tes = require('./lib/tes'); -let toMilliseconds = require('../../lib/to_milliseconds'); +const _ = require('lodash'); +const Chainable = require('../../lib/classes/chainable'); +const ses = require('./lib/ses'); +const des = require('./lib/des'); +const tes = require('./lib/tes'); +const toMilliseconds = require('../../lib/to_milliseconds'); module.exports = new Chainable('holt', { args: [ @@ -56,7 +56,7 @@ module.exports = new Chainable('holt', { purpose of anomaly detection. Note that nulls will be filled with forecasted values. Deal with it.`, fn: function expsmoothFn(args, tlConfig) { - let newSeries = _.cloneDeep(args.byName.inputSeries); + const newSeries = _.cloneDeep(args.byName.inputSeries); const alpha = args.byName.alpha; const beta = args.byName.beta; @@ -71,7 +71,7 @@ module.exports = new Chainable('holt', { // points exponentially degrade relative to the alpha, eg: // 0.8^1, 0.8^2, 0.8^3, etc - let times = _.map(series.data, 0); + const times = _.map(series.data, 0); let points = _.map(series.data, 1); if (alpha != null && beta == null && gamma == null) { diff --git a/src/core_plugins/timelion/server/series_functions/holt/lib/des.js b/src/core_plugins/timelion/server/series_functions/holt/lib/des.js index 28ee345584a93..e2559f49222d9 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/lib/des.js +++ b/src/core_plugins/timelion/server/series_functions/holt/lib/des.js @@ -1,4 +1,4 @@ -let _ = require('lodash'); +const _ = require('lodash'); module.exports = function des(points, alpha, beta) { let level; @@ -13,7 +13,7 @@ module.exports = function des(points, alpha, beta) { throw new Error ('You need at least 2 points to use double exponential smoothing'); } - let smoothedPoints = _.map(points, (point, i) => { + const smoothedPoints = _.map(points, (point, i) => { if (i === 0) { return point; } diff --git a/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js b/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js index e5e9dd46691c5..52173abf67eeb 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js +++ b/src/core_plugins/timelion/server/series_functions/holt/lib/ses.js @@ -8,7 +8,7 @@ module.exports = function ses(points, alpha) { let origin; let level; - let smoothedPoints = _.reduce(points, (result, point, i) => { + const smoothedPoints = _.reduce(points, (result, point, i) => { if (i === 0) { origin = point; level = point; diff --git a/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js b/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js index b634ff229103f..61c1afc3e2dd1 100644 --- a/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js +++ b/src/core_plugins/timelion/server/series_functions/holt/lib/tes.js @@ -8,13 +8,13 @@ Hourly data might have: - Annual seasonality (frequency=24×365.25=8766) */ -let _ = require('lodash'); +const _ = require('lodash'); // Uh, I don't think this will work when you have nulls in the initial seasonal components function initSeasonalComponents(samplePoints, seasonLength) { - let sampledSeasonCount = samplePoints.length / seasonLength; + const sampledSeasonCount = samplePoints.length / seasonLength; let currentSeason = []; - let seasonalAverages = _.reduce(samplePoints, (result, point, i) => { + const seasonalAverages = _.reduce(samplePoints, (result, point, i) => { currentSeason.push(point); // If this is the end of the season, add it to the result; if (i % seasonLength === seasonLength - 1) { @@ -25,7 +25,7 @@ function initSeasonalComponents(samplePoints, seasonLength) { return result; }, []); - let seasonals = _.times(seasonLength, (i) => { + const seasonals = _.times(seasonLength, (i) => { let sumOfValsOverAvg = 0; _.times(sampledSeasonCount, (j) => { sumOfValsOverAvg += samplePoints[seasonLength * j + i] - seasonalAverages[j]; @@ -49,15 +49,15 @@ function initTrend(samplePoints, seasonLength) { module.exports = function tes(points, alpha, beta, gamma, seasonLength, seasonsToSample) { - let samplePoints = points.slice(0, seasonLength * seasonsToSample); - let seasonals = initSeasonalComponents(samplePoints, seasonLength); + const samplePoints = points.slice(0, seasonLength * seasonsToSample); + const seasonals = initSeasonalComponents(samplePoints, seasonLength); let level; let prevLevel; let trend; let prevTrend; let unknownCount = 0; - let result = _.map(points, (point, i) => { + const result = _.map(points, (point, i) => { const seasonalPosition = i % seasonLength; // For the first samplePoints.length we use the actual points // After that we switch to the forecast diff --git a/src/core_plugins/timelion/server/series_functions/label.js b/src/core_plugins/timelion/server/series_functions/label.js index fbc5d3c237760..2253a0f4f2d8f 100644 --- a/src/core_plugins/timelion/server/series_functions/label.js +++ b/src/core_plugins/timelion/server/series_functions/label.js @@ -1,7 +1,7 @@ -let alter = require('../lib/alter.js'); -let util = require('util'); +const alter = require('../lib/alter.js'); +const util = require('util'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('label', { args: [ { @@ -21,7 +21,7 @@ module.exports = new Chainable('label', { ], help: 'Change the label of the series. Use %s reference the existing label', fn: function labelFn(args) { - let config = args.byName; + const config = args.byName; return alter(args, function (eachSeries) { if (config.regex) { eachSeries.label = eachSeries.label.replace(new RegExp(config.regex), config.label); diff --git a/src/core_plugins/timelion/server/series_functions/legend.js b/src/core_plugins/timelion/server/series_functions/legend.js index faa6f81884698..5efe2b18b4bc9 100644 --- a/src/core_plugins/timelion/server/series_functions/legend.js +++ b/src/core_plugins/timelion/server/series_functions/legend.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); +const alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('legend', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/lines.js b/src/core_plugins/timelion/server/series_functions/lines.js index 720e4bfdaf066..ab742f663e4ed 100644 --- a/src/core_plugins/timelion/server/series_functions/lines.js +++ b/src/core_plugins/timelion/server/series_functions/lines.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); +const alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('lines', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/log.js b/src/core_plugins/timelion/server/series_functions/log.js index 88a90eefba9fc..6b1093c6b17e1 100644 --- a/src/core_plugins/timelion/server/series_functions/log.js +++ b/src/core_plugins/timelion/server/series_functions/log.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('log', { args: [ { @@ -16,9 +16,9 @@ module.exports = new Chainable('log', { ], help: 'Return the logarithm value of each value in the series list (default base: 10)', fn: function logFn(args) { - let config = args.byName; + const config = args.byName; return alter(args, function (eachSeries) { - let data = _.map(eachSeries.data, function (point) { + const data = _.map(eachSeries.data, function (point) { return [point[0], Math.log(point[1]) / Math.log(config.base || 10)]; }); eachSeries.data = data; diff --git a/src/core_plugins/timelion/server/series_functions/max.js b/src/core_plugins/timelion/server/series_functions/max.js index 2012f9b74daad..83baae28bdf90 100644 --- a/src/core_plugins/timelion/server/series_functions/max.js +++ b/src/core_plugins/timelion/server/series_functions/max.js @@ -1,6 +1,6 @@ -let reduce = require('../lib/reduce.js'); +const reduce = require('../lib/reduce.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('max', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/min.js b/src/core_plugins/timelion/server/series_functions/min.js index f5f4cce4dc14d..be1b37cd3b554 100644 --- a/src/core_plugins/timelion/server/series_functions/min.js +++ b/src/core_plugins/timelion/server/series_functions/min.js @@ -1,6 +1,6 @@ -let reduce = require('../lib/reduce.js'); +const reduce = require('../lib/reduce.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('min', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/movingaverage.js b/src/core_plugins/timelion/server/series_functions/movingaverage.js index 129ffb5f58515..ffdf37055f748 100644 --- a/src/core_plugins/timelion/server/series_functions/movingaverage.js +++ b/src/core_plugins/timelion/server/series_functions/movingaverage.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('movingaverage', { args: [ { @@ -24,15 +24,15 @@ module.exports = new Chainable('movingaverage', { return alter(args, function (eachSeries, _window, _position) { _position = _position || 'center'; - let validPositions = ['left', 'right', 'center']; + const validPositions = ['left', 'right', 'center']; if (!_.contains(validPositions, _position)) throw new Error('Valid positions are: ' + validPositions.join(', ')); - let pairs = eachSeries.data; - let pairsLen = pairs.length; + const pairs = eachSeries.data; + const pairsLen = pairs.length; eachSeries.label = eachSeries.label + ' mvavg=' + _window; function toPoint(point, pairSlice) { - let average = _.chain(pairSlice) + const average = _.chain(pairSlice) .map(1).reduce(function (memo, num) { return (memo + num); }).value() / _window; @@ -41,8 +41,8 @@ module.exports = new Chainable('movingaverage', { } if (_position === 'center') { - let windowLeft = Math.floor(_window / 2); - let windowRight = _window - windowLeft; + const windowLeft = Math.floor(_window / 2); + const windowRight = _window - windowLeft; eachSeries.data = _.map(pairs, function (point, i) { if (i < windowLeft || i >= pairsLen - windowRight) return [point[0], null]; return toPoint(point, pairs.slice(i - windowLeft, i + windowRight)); diff --git a/src/core_plugins/timelion/server/series_functions/movingstd.js b/src/core_plugins/timelion/server/series_functions/movingstd.js index 9dc7270be8fbc..b4d03f84e2b8a 100644 --- a/src/core_plugins/timelion/server/series_functions/movingstd.js +++ b/src/core_plugins/timelion/server/series_functions/movingstd.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('movingstd', { args: [ { @@ -19,19 +19,19 @@ module.exports = new Chainable('movingstd', { fn: function movingstdFn(args) { return alter(args, function (eachSeries, _window) { - let pairs = eachSeries.data; + const pairs = eachSeries.data; eachSeries.data = _.map(pairs, function (point, i) { if (i < _window) { return [point[0], null]; } - let average = _.chain(pairs.slice(i - _window, i)) + const average = _.chain(pairs.slice(i - _window, i)) .map(function (point) { return point[1]; }).reduce(function (memo, num) { return (memo + num); }).value() / _window; - let variance = _.chain(pairs.slice(i - _window, i)) + const variance = _.chain(pairs.slice(i - _window, i)) .map(function (point) { return point[1]; }).reduce(function (memo, num) { diff --git a/src/core_plugins/timelion/server/series_functions/multiply.js b/src/core_plugins/timelion/server/series_functions/multiply.js index f88b7dcb5eafa..f773cd9883b7a 100644 --- a/src/core_plugins/timelion/server/series_functions/multiply.js +++ b/src/core_plugins/timelion/server/series_functions/multiply.js @@ -1,6 +1,6 @@ -let reduce = require('../lib/reduce.js'); +const reduce = require('../lib/reduce.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('multiply', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/points.js b/src/core_plugins/timelion/server/series_functions/points.js index 9bfd4f1c21537..743c490732b35 100644 --- a/src/core_plugins/timelion/server/series_functions/points.js +++ b/src/core_plugins/timelion/server/series_functions/points.js @@ -1,7 +1,7 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('points', { args: [ { @@ -58,7 +58,7 @@ module.exports = new Chainable('points', { } symbol = symbol || 'circle'; - let validSymbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; + const validSymbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; if (!_.contains(['triangle', 'cross', 'square', 'diamond', 'circle'], symbol)) { throw new Error('Valid symbols are: ' + validSymbols.join(', ')); } diff --git a/src/core_plugins/timelion/server/series_functions/precision.js b/src/core_plugins/timelion/server/series_functions/precision.js index 64a601298d32c..38b1e760f616a 100644 --- a/src/core_plugins/timelion/server/series_functions/precision.js +++ b/src/core_plugins/timelion/server/series_functions/precision.js @@ -1,8 +1,8 @@ -let reduce = require('../lib/reduce.js'); -let alter = require('../lib/alter.js'); +const reduce = require('../lib/reduce.js'); +const alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('precision', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/props.js b/src/core_plugins/timelion/server/series_functions/props.js index 52edaad703e6b..869c0121176e9 100644 --- a/src/core_plugins/timelion/server/series_functions/props.js +++ b/src/core_plugins/timelion/server/series_functions/props.js @@ -1,12 +1,12 @@ -let alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); -let _ = require('lodash'); +const alter = require('../lib/alter.js'); +const Chainable = require('../lib/classes/chainable'); +const _ = require('lodash'); function unflatten(data) { if (Object(data) !== data || _.isArray(data)) return data; - let regex = new RegExp(/\.?([^.\[\]]+)|\[(\d+)\]/g); - let result = {}; + const regex = new RegExp(/\.?([^.\[\]]+)|\[(\d+)\]/g); + const result = {}; _.each(data, function (val, p) { let cur = result; let prop = ''; @@ -43,7 +43,7 @@ module.exports = new Chainable('props', { // They will be passed as args._extended:{} help: 'Use at your own risk, sets arbitrary properties on the series. For example .props(label=bears!)', fn: function firstFn(args) { - let properties = unflatten(_.omit(args.byName, 'inputSeries', 'global')); + const properties = unflatten(_.omit(args.byName, 'inputSeries', 'global')); if (args.byName.global) { _.assign(args.byName.inputSeries, properties); diff --git a/src/core_plugins/timelion/server/series_functions/quandl.js b/src/core_plugins/timelion/server/series_functions/quandl.js index d209e1db0b87f..32a80fbc288b5 100644 --- a/src/core_plugins/timelion/server/series_functions/quandl.js +++ b/src/core_plugins/timelion/server/series_functions/quandl.js @@ -1,11 +1,11 @@ -let _ = require('lodash'); -let fetch = require('node-fetch'); -let moment = require('moment'); +const _ = require('lodash'); +const fetch = require('node-fetch'); +const moment = require('moment'); fetch.Promise = require('bluebird'); //var parseDateMath = require('../utils/date_math.js'); -let Datasource = require('../lib/classes/datasource'); +const Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('quandl', { @@ -27,14 +27,14 @@ module.exports = new Datasource ('quandl', { Pull data from quandl.com using the quandl code. Set "timelion:quandl.key" to your free API key in Kibana's Advanced Settings. The API has a really low rate limit without a key.`, fn: function quandlFn(args, tlConfig) { - let intervalMap = { + const intervalMap = { '1d': 'daily', '1w': 'weekly', '1M': 'monthly', '1y': 'annual', }; - let config = _.defaults(args.byName, { + const config = _.defaults(args.byName, { code: 'WIKI/AAPL', position: 1, interval: intervalMap[tlConfig.time.interval], @@ -46,7 +46,7 @@ module.exports = new Datasource ('quandl', { '. quandl() supports: ' + _.keys(intervalMap).join(', ')); } - let time = { + const time = { min: moment.utc(tlConfig.time.from).format('YYYY-MM-DD'), max: moment.utc(tlConfig.time.to).format('YYYY-MM-DD') }; @@ -58,7 +58,7 @@ module.exports = new Datasource ('quandl', { // 4. close // 5. volume - let URL = 'https://www.quandl.com/api/v1/datasets/' + config.code + '.json' + + const URL = 'https://www.quandl.com/api/v1/datasets/' + config.code + '.json' + '?sort_order=asc' + '&trim_start=' + time.min + '&trim_end=' + time.max + @@ -66,7 +66,7 @@ module.exports = new Datasource ('quandl', { '&auth_token=' + config.apikey; return fetch(URL).then(function (resp) { return resp.json(); }).then(function (resp) { - let data = _.map(resp.data, function (bucket) { + const data = _.map(resp.data, function (bucket) { return [moment(bucket[0]).valueOf(), bucket[config.position]]; }); diff --git a/src/core_plugins/timelion/server/series_functions/range.js b/src/core_plugins/timelion/server/series_functions/range.js index f0747f1966226..1fc51228c2c62 100644 --- a/src/core_plugins/timelion/server/series_functions/range.js +++ b/src/core_plugins/timelion/server/series_functions/range.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('range', { args: [ { @@ -21,13 +21,13 @@ module.exports = new Chainable('range', { help: 'Changes the max and min of a series while keeping the same shape', fn: function range(args) { return alter(args, function (eachSeries) { - let values = _.map(eachSeries.data, 1); - let min = _.min(values); - let max = _.max(values); + const values = _.map(eachSeries.data, 1); + const min = _.min(values); + const max = _.max(values); // newvalue= (max'-min')/(max-min)*(value-min)+min'. - let data = _.map(eachSeries.data, function (point) { - let val = (args.byName.max - args.byName.min) / + const data = _.map(eachSeries.data, function (point) { + const val = (args.byName.max - args.byName.min) / (max - min) * (point[1] - min) + args.byName.min; return [point[0], val]; }); diff --git a/src/core_plugins/timelion/server/series_functions/scale_interval.js b/src/core_plugins/timelion/server/series_functions/scale_interval.js index 77b2d2deacc6b..9e2771fc366f6 100644 --- a/src/core_plugins/timelion/server/series_functions/scale_interval.js +++ b/src/core_plugins/timelion/server/series_functions/scale_interval.js @@ -1,8 +1,8 @@ -let alter = require('../lib/alter.js'); -let toMS = require('../lib/to_milliseconds.js'); +const alter = require('../lib/alter.js'); +const toMS = require('../lib/to_milliseconds.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('scale_interval', { args: [ { @@ -17,11 +17,11 @@ module.exports = new Chainable('scale_interval', { ], help: 'Changes scales a value (usually a sum or a count) to a new interval. For example, as a per-second rate', fn: function scaleIntervalFn(args, tlConfig) { - let currentInterval = toMS(tlConfig.time.interval); - let scaleInterval = toMS(args.byName.interval); + const currentInterval = toMS(tlConfig.time.interval); + const scaleInterval = toMS(args.byName.interval); return alter(args, function (eachSeries) { - let data = _.map(eachSeries.data, function (point) { + const data = _.map(eachSeries.data, function (point) { return [point[0], (point[1] / currentInterval) * scaleInterval]; }); eachSeries.data = data; diff --git a/src/core_plugins/timelion/server/series_functions/static.js b/src/core_plugins/timelion/server/series_functions/static.js index 32a69a5766a4f..02b7bf47b11fe 100644 --- a/src/core_plugins/timelion/server/series_functions/static.js +++ b/src/core_plugins/timelion/server/series_functions/static.js @@ -1,8 +1,8 @@ -let _ = require('lodash'); -let fetch = require('node-fetch'); -let moment = require('moment'); -let Datasource = require('../lib/classes/datasource'); -let Promise = require('bluebird'); +const _ = require('lodash'); +const fetch = require('node-fetch'); +const moment = require('moment'); +const Datasource = require('../lib/classes/datasource'); +const Promise = require('bluebird'); module.exports = new Datasource ('static', { @@ -24,12 +24,12 @@ module.exports = new Datasource ('static', { fn: function staticFn(args, tlConfig) { let data; - let target = tlConfig.getTargetSeries(); + const target = tlConfig.getTargetSeries(); if (typeof args.byName.value === 'string') { - let points = args.byName.value.split(':'); - let begin = _.first(target)[0]; - let end = _.last(target)[0]; - let step = (end - begin) / (points.length - 1); + const points = args.byName.value.split(':'); + const begin = _.first(target)[0]; + const end = _.last(target)[0]; + const step = (end - begin) / (points.length - 1); data = _.map(points, function (point, i) { return [begin + (i * step), parseFloat(point)]; }); diff --git a/src/core_plugins/timelion/server/series_functions/subtract.js b/src/core_plugins/timelion/server/series_functions/subtract.js index 4848f502c59cc..1c4d2e19b19db 100644 --- a/src/core_plugins/timelion/server/series_functions/subtract.js +++ b/src/core_plugins/timelion/server/series_functions/subtract.js @@ -1,7 +1,7 @@ -let reduce = require('../lib/reduce.js'); +const reduce = require('../lib/reduce.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('subtract', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/sum.js b/src/core_plugins/timelion/server/series_functions/sum.js index 0b0f258083c04..235540281bdb0 100644 --- a/src/core_plugins/timelion/server/series_functions/sum.js +++ b/src/core_plugins/timelion/server/series_functions/sum.js @@ -1,6 +1,6 @@ -let reduce = require('../lib/reduce.js'); +const reduce = require('../lib/reduce.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('sum', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/title.js b/src/core_plugins/timelion/server/series_functions/title.js index c53c4caa7d4e6..1ab495005269e 100644 --- a/src/core_plugins/timelion/server/series_functions/title.js +++ b/src/core_plugins/timelion/server/series_functions/title.js @@ -1,5 +1,5 @@ -let alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const alter = require('../lib/alter.js'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('title', { args: [ { diff --git a/src/core_plugins/timelion/server/series_functions/trend/index.js b/src/core_plugins/timelion/server/series_functions/trend/index.js index fe8848a6ac331..958e807241de1 100644 --- a/src/core_plugins/timelion/server/series_functions/trend/index.js +++ b/src/core_plugins/timelion/server/series_functions/trend/index.js @@ -1,8 +1,8 @@ -let _ = require('lodash'); -let Chainable = require('../../lib/classes/chainable'); +const _ = require('lodash'); +const Chainable = require('../../lib/classes/chainable'); import * as regress from './lib/regress'; -let validRegressions = { +const validRegressions = { linear: 'linear', log: 'logarithmic', }; @@ -33,7 +33,7 @@ module.exports = new Chainable('trend', { ], help: 'Draws a trend line using a specified regression algorithm', fn: function absFn(args) { - let newSeries = _.cloneDeep(args.byName.inputSeries); + const newSeries = _.cloneDeep(args.byName.inputSeries); _.each(newSeries.list, function (series) { const length = series.data.length; diff --git a/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js b/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js index 5bb4119e5fc21..d65a66e2b7a3d 100644 --- a/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js +++ b/src/core_plugins/timelion/server/series_functions/trend/lib/regress.js @@ -4,7 +4,7 @@ * Licensed under the MIT license. */ -let _ = require('lodash'); +const _ = require('lodash'); function sum(data, fn) { return _.reduce(data, function (sum, d) { @@ -25,34 +25,34 @@ function mapTuples(data, fn) { } export function linear(data) { - let xSum = sum(data, (d) => {return d[0]; }); - let ySum = sum(data, (d) => {return d[1]; }); - let xSqSum = sum(data, (d) => {return d[0] * d[0]; }); - let xySum = sum(data, (d) => {return d[0] * d[1]; }); - let observations = count(data); + const xSum = sum(data, (d) => {return d[0]; }); + const ySum = sum(data, (d) => {return d[1]; }); + const xSqSum = sum(data, (d) => {return d[0] * d[0]; }); + const xySum = sum(data, (d) => {return d[0] * d[1]; }); + const observations = count(data); - let gradient = + const gradient = ((observations * xySum) - (xSum * ySum)) / ((observations * xSqSum) - (xSum * xSum)); - let intercept = + const intercept = (ySum / observations) - (gradient * xSum) / observations; return mapTuples(data, (d) => { return d[0] * gradient + intercept; }); } export function log(data) { - let logXSum = sum(data, (d) => {return Math.log(d[0]); }); - let yLogXSum = sum(data, (d) => {return d[1] * Math.log(d[0]); }); - let ySum = sum(data, (d) => {return d[1]; }); - let logXsqSum = sum(data, (d) => {return Math.pow(Math.log(d[0]), 2); }); - let observations = count(data); + const logXSum = sum(data, (d) => {return Math.log(d[0]); }); + const yLogXSum = sum(data, (d) => {return d[1] * Math.log(d[0]); }); + const ySum = sum(data, (d) => {return d[1]; }); + const logXsqSum = sum(data, (d) => {return Math.pow(Math.log(d[0]), 2); }); + const observations = count(data); - let b = + const b = ((observations * yLogXSum) - (ySum * logXSum)) / ((observations * logXsqSum) - (logXSum * logXSum)); - let a = + const a = (ySum - b * logXSum) / observations; diff --git a/src/core_plugins/timelion/server/series_functions/trim.js b/src/core_plugins/timelion/server/series_functions/trim.js index 64bae6d2b086a..73ffbc6658b46 100644 --- a/src/core_plugins/timelion/server/series_functions/trim.js +++ b/src/core_plugins/timelion/server/series_functions/trim.js @@ -1,7 +1,7 @@ -let alter = require('../lib/alter.js'); -let _ = require('lodash'); -let Chainable = require('../lib/classes/chainable'); -let argType = require('../handlers/lib/arg_type.js'); +const alter = require('../lib/alter.js'); +const _ = require('lodash'); +const Chainable = require('../lib/classes/chainable'); +const argType = require('../handlers/lib/arg_type.js'); module.exports = new Chainable('trim', { args: [ @@ -22,7 +22,7 @@ module.exports = new Chainable('trim', { ], help: 'Set N buckets at the start or end of a series to null to fit the "partial bucket issue"', fn: function conditionFn(args) { - let config = args.byName; + const config = args.byName; if (config.start == null) config.start = 1; if (config.end == null) config.end = 1; diff --git a/src/core_plugins/timelion/server/series_functions/worldbank.js b/src/core_plugins/timelion/server/series_functions/worldbank.js index 3301b70e68e03..fd15c95f2ad75 100644 --- a/src/core_plugins/timelion/server/series_functions/worldbank.js +++ b/src/core_plugins/timelion/server/series_functions/worldbank.js @@ -1,7 +1,7 @@ -let _ = require('lodash'); -let fetch = require('node-fetch'); -let moment = require('moment'); -let Datasource = require('../lib/classes/datasource'); +const _ = require('lodash'); +const fetch = require('node-fetch'); +const moment = require('moment'); +const Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('worldbank', { args: [ @@ -22,16 +22,16 @@ module.exports = new Datasource ('worldbank', { fn: function worldbank(args, tlConfig) { // http://api.worldbank.org/en/countries/ind;chn/indicators/DPANUSSPF?date=2000:2006&MRV=5 - let config = _.defaults(args.byName, { + const config = _.defaults(args.byName, { code: 'countries/wld/indicators/SP.POP.TOTL' }); - let time = { + const time = { min: moment(tlConfig.time.from).format('YYYY'), max: moment(tlConfig.time.to).format('YYYY') }; - let URL = 'http://api.worldbank.org/' + config.code + + const URL = 'http://api.worldbank.org/' + config.code + '?date=' + time.min + ':' + time.max + '&format=json' + '&per_page=1000'; @@ -39,9 +39,9 @@ module.exports = new Datasource ('worldbank', { return fetch(URL).then(function (resp) { return resp.json(); }).then(function (resp) { let hasData = false; - let respSeries = resp[1]; + const respSeries = resp[1]; - let deduped = {}; + const deduped = {}; let description; _.each (respSeries, function (bucket) { if (bucket.value != null) hasData = true; @@ -49,7 +49,7 @@ module.exports = new Datasource ('worldbank', { deduped[bucket.date] = bucket.value; }); - let data = _.compact(_.map(deduped, function (val, date) { + const data = _.compact(_.map(deduped, function (val, date) { // Discard nulls if (val == null) return; return [moment(date, 'YYYY').valueOf(), Number(val)]; diff --git a/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js b/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js index 8e5ffb4e30005..9d20866cd058d 100644 --- a/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js +++ b/src/core_plugins/timelion/server/series_functions/worldbank_indicators.js @@ -1,9 +1,9 @@ -let _ = require('lodash'); -let fetch = require('node-fetch'); -let moment = require('moment'); -let worldbank = require('./worldbank.js'); -let Promise = require('bluebird'); -let Datasource = require('../lib/classes/datasource'); +const _ = require('lodash'); +const fetch = require('node-fetch'); +const moment = require('moment'); +const worldbank = require('./worldbank.js'); +const Promise = require('bluebird'); +const Datasource = require('../lib/classes/datasource'); module.exports = new Datasource ('worldbank_indicators', { @@ -27,15 +27,15 @@ module.exports = new Datasource ('worldbank_indicators', { mostly yearly data, and often has no data for the current year. Try offset=-1y if you get no data for recent time ranges.`, fn: function worldbankIndicators(args, tlConfig) { - let config = _.defaults(args.byName, { + const config = _.defaults(args.byName, { country: 'wld', indicator: 'SP.POP.TOTL' }); - let countries = config.country.split(':'); - let seriesLists = _.map(countries, function (country) { - let code = 'countries/' + country + '/indicators/' + config.indicator; - let wbArgs = [code]; + const countries = config.country.split(':'); + const seriesLists = _.map(countries, function (country) { + const code = 'countries/' + country + '/indicators/' + config.indicator; + const wbArgs = [code]; wbArgs.byName = {code: code}; return worldbank.timelionFn(wbArgs, tlConfig); }); diff --git a/src/core_plugins/timelion/server/series_functions/yaxis.js b/src/core_plugins/timelion/server/series_functions/yaxis.js index 5f6c781fad0cf..fef9e943d0dd7 100644 --- a/src/core_plugins/timelion/server/series_functions/yaxis.js +++ b/src/core_plugins/timelion/server/series_functions/yaxis.js @@ -1,6 +1,6 @@ -let alter = require('../lib/alter.js'); +const alter = require('../lib/alter.js'); -let Chainable = require('../lib/classes/chainable'); +const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('yaxis', { args: [ { @@ -49,7 +49,7 @@ module.exports = new Chainable('yaxis', { eachSeries._global.yaxes = eachSeries._global.yaxes || []; eachSeries._global.yaxes[yaxis - 1] = eachSeries._global.yaxes[yaxis - 1] || {}; - let myAxis = eachSeries._global.yaxes[yaxis - 1]; + const myAxis = eachSeries._global.yaxes[yaxis - 1]; myAxis.position = position || (yaxis % 2 ? 'left' : 'right'); myAxis.min = min == null ? 0 : min; myAxis.max = max; diff --git a/src/fixtures/agg_resp/geohash_grid.js b/src/fixtures/agg_resp/geohash_grid.js index 33a446ff360b2..b627b180964c1 100644 --- a/src/fixtures/agg_resp/geohash_grid.js +++ b/src/fixtures/agg_resp/geohash_grid.js @@ -17,7 +17,7 @@ export default function GeoHashGridAggResponseFixture() { // }, // }); - let geoHashCharts = _.union( + const geoHashCharts = _.union( _.range(48, 57), // 0-9 _.range(65, 90), // A-Z _.range(97, 122) // a-z @@ -25,15 +25,15 @@ export default function GeoHashGridAggResponseFixture() { let totalDocCount = 0; - let tags = _.times(_.random(4, 20), function (i) { + const tags = _.times(_.random(4, 20), function (i) { // random number of tags let docCount = 0; - let buckets = _.times(_.random(40, 200), function () { + const buckets = _.times(_.random(40, 200), function () { return _.sample(geoHashCharts, 3).join(''); }) .sort() .map(function (geoHash) { - let count = _.random(1, 5000); + const count = _.random(1, 5000); totalDocCount += count; docCount += count; diff --git a/src/fixtures/fake_chart_events.js b/src/fixtures/fake_chart_events.js index 383a61c900815..9e4db976c64e6 100644 --- a/src/fixtures/fake_chart_events.js +++ b/src/fixtures/fake_chart_events.js @@ -1,4 +1,4 @@ -let results = {}; +const results = {}; results.timeSeries = { data: { diff --git a/src/fixtures/fake_hierarchical_data.js b/src/fixtures/fake_hierarchical_data.js index 2b1096cc9c271..d7d734214d4fd 100644 --- a/src/fixtures/fake_hierarchical_data.js +++ b/src/fixtures/fake_hierarchical_data.js @@ -1,4 +1,4 @@ -let data = { }; +const data = { }; data.metricOnly = { hits: { total: 1000, hits: [], max_score: 0 }, diff --git a/src/fixtures/fake_row.js b/src/fixtures/fake_row.js index 032fe0f1a9235..c7acfd4446774 100644 --- a/src/fixtures/fake_row.js +++ b/src/fixtures/fake_row.js @@ -1,5 +1,5 @@ import _ from 'lodash'; -let longString = Array(200).join('_'); +const longString = Array(200).join('_'); export default function (id, mapping) { function fakeVals(type) { diff --git a/src/fixtures/mock_courier.js b/src/fixtures/mock_courier.js index ef68696693551..942475fccb4e5 100644 --- a/src/fixtures/mock_courier.js +++ b/src/fixtures/mock_courier.js @@ -3,11 +3,11 @@ import sinon from 'auto-release-sinon'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; export default function (Private, Promise) { - let indexPatterns = Private(FixturesStubbedLogstashIndexPatternProvider); - let getIndexPatternStub = sinon.stub(); + const indexPatterns = Private(FixturesStubbedLogstashIndexPatternProvider); + const getIndexPatternStub = sinon.stub(); getIndexPatternStub.returns(Promise.resolve(indexPatterns)); - let courier = { + const courier = { indexPatterns: { get: getIndexPatternStub }, getStub: getIndexPatternStub }; diff --git a/src/fixtures/mock_ui_state.js b/src/fixtures/mock_ui_state.js index 5f5b90e38eb3d..7614896cceb6f 100644 --- a/src/fixtures/mock_ui_state.js +++ b/src/fixtures/mock_ui_state.js @@ -1,5 +1,5 @@ import _ from 'lodash'; -let keys = {}; +const keys = {}; export default { get: function (path, def) { return keys[path] == null ? def : keys[path]; diff --git a/src/fixtures/stubbed_doc_source_response.js b/src/fixtures/stubbed_doc_source_response.js index 5bed6d41af348..99055142e5bb1 100644 --- a/src/fixtures/stubbed_doc_source_response.js +++ b/src/fixtures/stubbed_doc_source_response.js @@ -1,7 +1,7 @@ import FixturesLogstashFieldsProvider from 'fixtures/logstash_fields'; function stubbedDocSourceResponse(Private) { - let mockLogstashFields = Private(FixturesLogstashFieldsProvider); + const mockLogstashFields = Private(FixturesLogstashFieldsProvider); return function (id, index) { index = index || '.kibana'; diff --git a/src/fixtures/stubbed_logstash_index_pattern.js b/src/fixtures/stubbed_logstash_index_pattern.js index 8377132b6d8ea..daa6b37dc607d 100644 --- a/src/fixtures/stubbed_logstash_index_pattern.js +++ b/src/fixtures/stubbed_logstash_index_pattern.js @@ -3,21 +3,21 @@ import TestUtilsStubIndexPatternProvider from 'test_utils/stub_index_pattern'; import IndexPatternsFieldTypesProvider from 'ui/index_patterns/_field_types'; import FixturesLogstashFieldsProvider from 'fixtures/logstash_fields'; export default function stubbedLogstashIndexPatternService(Private) { - let StubIndexPattern = Private(TestUtilsStubIndexPatternProvider); - let fieldTypes = Private(IndexPatternsFieldTypesProvider); - let mockLogstashFields = Private(FixturesLogstashFieldsProvider); + const StubIndexPattern = Private(TestUtilsStubIndexPatternProvider); + const fieldTypes = Private(IndexPatternsFieldTypesProvider); + const mockLogstashFields = Private(FixturesLogstashFieldsProvider); - let fields = mockLogstashFields.map(function (field) { + const fields = mockLogstashFields.map(function (field) { field.displayName = field.name; - let type = fieldTypes.byName[field.type]; + const type = fieldTypes.byName[field.type]; if (!type) throw new TypeError('unknown type ' + field.type); if (!_.has(field, 'sortable')) field.sortable = type.sortable; if (!_.has(field, 'filterable')) field.filterable = type.filterable; return field; }); - let indexPattern = new StubIndexPattern('logstash-*', 'time', fields); + const indexPattern = new StubIndexPattern('logstash-*', 'time', fields); indexPattern.id = 'logstash-*'; return indexPattern; diff --git a/src/fixtures/stubbed_search_source.js b/src/fixtures/stubbed_search_source.js index 118aaede15047..284a0bf00bbea 100644 --- a/src/fixtures/stubbed_search_source.js +++ b/src/fixtures/stubbed_search_source.js @@ -4,7 +4,7 @@ import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logsta export default function stubSearchSource(Private, $q, Promise) { let deferedResult = $q.defer(); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); return { sort: sinon.spy(), diff --git a/src/fixtures/vislib/_vis_fixture.js b/src/fixtures/vislib/_vis_fixture.js index 79a82dfe52414..3214cf0cc0747 100644 --- a/src/fixtures/vislib/_vis_fixture.js +++ b/src/fixtures/vislib/_vis_fixture.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import $ from 'jquery'; import VislibVisProvider from 'ui/vislib/vis'; -let $visCanvas = $('
') +const $visCanvas = $('
') .attr('id', 'vislib-vis-fixtures') .css({ height: '500px', @@ -17,7 +17,7 @@ let $visCanvas = $('
') .appendTo('body'); let count = 0; -let visHeight = $visCanvas.height(); +const visHeight = $visCanvas.height(); $visCanvas.new = function () { count += 1; @@ -33,7 +33,7 @@ afterEach(function () { module.exports = function VislibFixtures(Private) { return function (visLibParams) { - let Vis = Private(VislibVisProvider); + const Vis = Private(VislibVisProvider); return new Vis($visCanvas.new(), _.defaults({}, visLibParams || {}, { shareYAxis: true, addTooltip: true, diff --git a/src/optimize/babel_options.build.js b/src/optimize/babel_options.build.js index 885a318ab84d1..ec3f11f6f1528 100644 --- a/src/optimize/babel_options.build.js +++ b/src/optimize/babel_options.build.js @@ -1,5 +1,5 @@ import { cloneDeep } from 'lodash'; -let fromRoot = require('path').resolve.bind(null, __dirname, '../../'); +const fromRoot = require('path').resolve.bind(null, __dirname, '../../'); if (!process.env.BABEL_CACHE_PATH) { process.env.BABEL_CACHE_PATH = fromRoot('optimize/.babelcache.json'); diff --git a/src/optimize/babel_options.js b/src/optimize/babel_options.js index e562700da3708..903701133ae59 100644 --- a/src/optimize/babel_options.js +++ b/src/optimize/babel_options.js @@ -1,8 +1,8 @@ // this file is not transpiled 'use strict'; // eslint-disable-line strict -let cloneDeep = require('lodash').cloneDeep; -let fromRoot = require('path').resolve.bind(null, __dirname, '../../'); +const cloneDeep = require('lodash').cloneDeep; +const fromRoot = require('path').resolve.bind(null, __dirname, '../../'); if (!process.env.BABEL_CACHE_PATH) { process.env.BABEL_CACHE_PATH = fromRoot('optimize/.babelcache.json'); diff --git a/src/optimize/base_optimizer.js b/src/optimize/base_optimizer.js index 5e0e79d3d72a2..66f3117934da3 100644 --- a/src/optimize/base_optimizer.js +++ b/src/optimize/base_optimizer.js @@ -12,7 +12,7 @@ import { inherits } from 'util'; import { defaults, transform } from 'lodash'; import { resolve } from 'path'; import { writeFile } from 'fs'; -let babelExclude = [/[\/\\](webpackShims|node_modules|bower_components)[\/\\]/]; +const babelExclude = [/[\/\\](webpackShims|node_modules|bower_components)[\/\\]/]; import pkg from '../../package.json'; class BaseOptimizer { @@ -47,14 +47,14 @@ class BaseOptimizer { async initCompiler() { if (this.compiler) return this.compiler; - let compilerConfig = this.getConfig(); + const compilerConfig = this.getConfig(); this.compiler = webpack(compilerConfig); this.compiler.plugin('done', stats => { if (!this.profile) return; - let path = resolve(this.env.workingDir, 'stats.json'); - let content = JSON.stringify(stats.toJson()); + const path = resolve(this.env.workingDir, 'stats.json'); + const content = JSON.stringify(stats.toJson()); writeFile(path, content, function (err) { if (err) throw err; }); @@ -64,8 +64,8 @@ class BaseOptimizer { } getConfig() { - let mapQ = this.sourceMaps ? '?sourceMap' : ''; - let mapQPre = mapQ ? mapQ + '&' : '?'; + const mapQ = this.sourceMaps ? '?sourceMap' : ''; + const mapQPre = mapQ ? mapQ + '&' : '?'; return { context: fromRoot('.'), @@ -177,7 +177,7 @@ class BaseOptimizer { } failedStatsToError(stats) { - let statFormatOpts = { + const statFormatOpts = { hash: false, // add the hash of the compilation version: false, // add webpack version information timings: false, // add timing information @@ -196,7 +196,7 @@ class BaseOptimizer { children: false, }; - let details = stats.toString(defaults({ colors: true }, statFormatOpts)); + const details = stats.toString(defaults({ colors: true }, statFormatOpts)); return Boom.create( 500, diff --git a/src/optimize/fs_optimizer.js b/src/optimize/fs_optimizer.js index 67e03c66c64a8..3e11b34acaed1 100644 --- a/src/optimize/fs_optimizer.js +++ b/src/optimize/fs_optimizer.js @@ -12,7 +12,7 @@ module.exports = class FsOptimizer extends BaseOptimizer { async run() { if (!this.compiler) await this.init(); - let stats = await fromNode(cb => { + const stats = await fromNode(cb => { this.compiler.run((err, stats) => { if (err || !stats) return cb(err); diff --git a/src/optimize/index.js b/src/optimize/index.js index a753ea40f8381..fa0028ffe4204 100644 --- a/src/optimize/index.js +++ b/src/optimize/index.js @@ -10,17 +10,17 @@ module.exports = async (kbnServer, server, config) => { // on the watch setup managed by the cli. It proxies all bundles/* requests to // the other server. The server on 5602 is long running, in order to prevent // complete rebuilds of the optimize content. - let lazy = config.get('optimize.lazy'); + const lazy = config.get('optimize.lazy'); if (lazy) { return await kbnServer.mixin(require('./lazy/lazy')); } - let bundles = kbnServer.bundles; + const bundles = kbnServer.bundles; server.exposeStaticDir('/bundles/{path*}', bundles.env.workingDir); await bundles.writeEntryFiles(); // in prod, only bundle when someing is missing or invalid - let invalidBundles = config.get('optimize.useBundleCache') ? await bundles.getInvalidBundles() : bundles; + const invalidBundles = config.get('optimize.useBundleCache') ? await bundles.getInvalidBundles() : bundles; // we might not have any work to do if (!invalidBundles.getIds().length) { @@ -32,7 +32,7 @@ module.exports = async (kbnServer, server, config) => { } // only require the FsOptimizer when we need to - let optimizer = new FsOptimizer({ + const optimizer = new FsOptimizer({ env: bundles.env, bundles: bundles, profile: config.get('optimize.profile'), @@ -46,9 +46,9 @@ module.exports = async (kbnServer, server, config) => { `Optimizing and caching ${bundles.desc()}. This may take a few minutes` ); - let start = Date.now(); + const start = Date.now(); await optimizer.run(); - let seconds = ((Date.now() - start) / 1000).toFixed(2); + const seconds = ((Date.now() - start) / 1000).toFixed(2); server.log(['info', 'optimize'], `Optimization of ${bundles.desc()} complete in ${seconds} seconds`); }; diff --git a/src/optimize/lazy/lazy_optimizer.js b/src/optimize/lazy/lazy_optimizer.js index ca7b052e392f6..62c4e2cec0e06 100644 --- a/src/optimize/lazy/lazy_optimizer.js +++ b/src/optimize/lazy/lazy_optimizer.js @@ -41,7 +41,7 @@ module.exports = class LazyOptimizer extends BaseOptimizer { return; } - let err = this.failedStatsToError(stats); + const err = this.failedStatsToError(stats); this.logRunFailure(err); this.build.failure(err); this.watching.invalidate(); @@ -54,7 +54,7 @@ module.exports = class LazyOptimizer extends BaseOptimizer { } }); - let buildPromise = this.build.get(); + const buildPromise = this.build.get(); if (this.prebuild) await buildPromise; this.initializing = false; @@ -75,7 +75,7 @@ module.exports = class LazyOptimizer extends BaseOptimizer { method: 'GET', handler: async (request, reply) => { try { - let path = await this.getPath(request.params.asset); + const path = await this.getPath(request.params.asset); return reply.file(path); } catch (error) { console.log(error.stack); diff --git a/src/optimize/lazy/optmzr_role.js b/src/optimize/lazy/optmzr_role.js index 8c6a653fe0937..30f5f30ac73de 100644 --- a/src/optimize/lazy/optmzr_role.js +++ b/src/optimize/lazy/optmzr_role.js @@ -3,7 +3,7 @@ import LazyOptimizer from './lazy_optimizer'; import { fromRoot } from '../../utils'; export default async (kbnServer, kibanaHapiServer, config) => { - let server = new LazyServer( + const server = new LazyServer( config.get('optimize.lazyHost'), config.get('optimize.lazyPort'), new LazyOptimizer({ @@ -20,7 +20,7 @@ export default async (kbnServer, kibanaHapiServer, config) => { let ready = false; - let sendReady = () => { + const sendReady = () => { if (!process.connected) return; process.send(['WORKER_BROADCAST', { optimizeReady: ready }]); }; diff --git a/src/optimize/lazy/proxy_role.js b/src/optimize/lazy/proxy_role.js index b9b0f26ed6a63..9ea0bceeec7c3 100644 --- a/src/optimize/lazy/proxy_role.js +++ b/src/optimize/lazy/proxy_role.js @@ -18,11 +18,11 @@ module.exports = (kbnServer, server, config) => { }); return fromNode(cb => { - let timeout = setTimeout(() => { + const timeout = setTimeout(() => { cb(new Error('Server timedout waiting for the optimizer to become ready')); }, config.get('optimize.lazyProxyTimeout')); - let waiting = once(() => { + const waiting = once(() => { server.log(['info', 'optimize'], 'Waiting for optimizer completion'); }); diff --git a/src/optimize/lazy/weird_control_flow.js b/src/optimize/lazy/weird_control_flow.js index ae37cce688283..b6ca267cdc720 100644 --- a/src/optimize/lazy/weird_control_flow.js +++ b/src/optimize/lazy/weird_control_flow.js @@ -51,7 +51,7 @@ module.exports = class WeirdControlFlow { } _flush(args) { - for (let fn of this.handlers.splice(0)) { + for (const fn of this.handlers.splice(0)) { fn.apply(null, args); } } diff --git a/src/server/config/__tests__/config.js b/src/server/config/__tests__/config.js index 0dc60f98f6004..ab2cc65bed201 100644 --- a/src/server/config/__tests__/config.js +++ b/src/server/config/__tests__/config.js @@ -14,7 +14,7 @@ import Joi from 'joi'; * */ -let data = { +const data = { test: { hosts: ['host-01', 'host-02'], client: { @@ -25,7 +25,7 @@ let data = { } }; -let schema = Joi.object({ +const schema = Joi.object({ test: Joi.object({ enable: Joi.boolean().default(true), hosts: Joi.array().items(Joi.string()), @@ -44,39 +44,39 @@ describe('lib/config/config', function () { describe('constructor', function () { it('should not allow any config if the schema is not passed', function () { - let config = new Config(); - let run = function () { + const config = new Config(); + const run = function () { config.set('something.enable', true); }; expect(run).to.throwException(); }); it('should allow keys in the schema', function () { - let config = new Config(schema); - let run = function () { + const config = new Config(schema); + const run = function () { config.set('test.client.host', 'http://localhost'); }; expect(run).to.not.throwException(); }); it('should not allow keys not in the schema', function () { - let config = new Config(schema); - let run = function () { + const config = new Config(schema); + const run = function () { config.set('paramNotDefinedInTheSchema', true); }; expect(run).to.throwException(); }); it('should not allow child keys not in the schema', function () { - let config = new Config(schema); - let run = function () { + const config = new Config(schema); + const run = function () { config.set('test.client.paramNotDefinedInTheSchema', true); }; expect(run).to.throwException(); }); it('should set defaults', function () { - let config = new Config(schema); + const config = new Config(schema); expect(config.get('test.enable')).to.be(true); expect(config.get('test.client.type')).to.be('datastore'); }); @@ -92,7 +92,7 @@ describe('lib/config/config', function () { it('should reset the config object with new values', function () { config.set(data); - let newData = config.get(); + const newData = config.get(); newData.test.enable = false; config.resetTo(newData); expect(config.get()).to.eql(newData); @@ -134,21 +134,21 @@ describe('lib/config/config', function () { }); it('should use an object to set config values', function () { - let hosts = ['host-01', 'host-02']; + const hosts = ['host-01', 'host-02']; config.set({ test: { enable: false, hosts: hosts } }); expect(config.get('test.enable')).to.be(false); expect(config.get('test.hosts')).to.eql(hosts); }); it('should use a flatten object to set config values', function () { - let hosts = ['host-01', 'host-02']; + const hosts = ['host-01', 'host-02']; config.set({ 'test.enable': false, 'test.hosts': hosts }); expect(config.get('test.enable')).to.be(false); expect(config.get('test.hosts')).to.eql(hosts); }); it('should override values with just the values present', function () { - let newData = _.cloneDeep(data); + const newData = _.cloneDeep(data); config.set(data); newData.test.enable = false; config.set({ test: { enable: false } }); @@ -156,7 +156,7 @@ describe('lib/config/config', function () { }); it('should thow an exception when setting a value with the wrong type', function (done) { - let run = function () { + const run = function () { config.set('test.enable', 'something'); }; expect(run).to.throwException(function (err) { @@ -179,7 +179,7 @@ describe('lib/config/config', function () { }); it('should return the whole config object when called without a key', function () { - let newData = _.cloneDeep(data); + const newData = _.cloneDeep(data); newData.test.enable = true; expect(config.get()).to.eql(newData); }); @@ -194,14 +194,14 @@ describe('lib/config/config', function () { }); it('should throw exception for unknown config values', function () { - let run = function () { + const run = function () { config.get('test.does.not.exist'); }; expect(run).to.throwException(/Unknown config key: test.does.not.exist/); }); it('should not throw exception for undefined known config values', function () { - let run = function getUndefValue() { + const run = function getUndefValue() { config.get('test.undefValue'); }; expect(run).to.not.throwException(); @@ -216,13 +216,13 @@ describe('lib/config/config', function () { }); it('should allow you to extend the schema at the top level', function () { - let newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); + const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema('myTest', newSchema); expect(config.get('myTest.test')).to.be(true); }); it('should allow you to extend the schema with a prefix', function () { - let newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); + const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema('prefix.myTest', newSchema); expect(config.get('prefix')).to.eql({ myTest: { test: true }}); expect(config.get('prefix.myTest')).to.eql({ test: true }); @@ -230,8 +230,8 @@ describe('lib/config/config', function () { }); it('should NOT allow you to extend the schema if somethign else is there', function () { - let newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); - let run = function () { + const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); + const run = function () { config.extendSchema('test', newSchema); }; expect(run).to.throwException(); @@ -241,7 +241,7 @@ describe('lib/config/config', function () { describe('#removeSchema(key)', function () { it('should completely remove the key', function () { - let config = new Config(Joi.object().keys({ + const config = new Config(Joi.object().keys({ a: Joi.number().default(1) })); @@ -251,7 +251,7 @@ describe('lib/config/config', function () { }); it('only removes existing keys', function () { - let config = new Config(Joi.object()); + const config = new Config(Joi.object()); expect(() => config.removeSchema('b')).to.throwException('Unknown schema'); }); diff --git a/src/server/config/__tests__/explode_by.js b/src/server/config/__tests__/explode_by.js index 3514413e575b6..52ab03e00d047 100644 --- a/src/server/config/__tests__/explode_by.js +++ b/src/server/config/__tests__/explode_by.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; describe('explode_by(dot, flatObject)', function () { it('should explode a flatten object with dots', function () { - let flatObject = { + const flatObject = { 'test.enable': true, 'test.hosts': ['host-01', 'host-02'] }; @@ -17,7 +17,7 @@ describe('explode_by(dot, flatObject)', function () { }); it('should explode a flatten object with slashes', function () { - let flatObject = { + const flatObject = { 'test/enable': true, 'test/hosts': ['host-01', 'host-02'] }; diff --git a/src/server/config/__tests__/flatten_with.js b/src/server/config/__tests__/flatten_with.js index 9dc40fc08097e..78864e490bc30 100644 --- a/src/server/config/__tests__/flatten_with.js +++ b/src/server/config/__tests__/flatten_with.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; describe('flatten_with(dot, nestedObj)', function () { it('should flatten object with dot', function () { - let nestedObj = { + const nestedObj = { test: { enable: true, hosts: ['host-01', 'host-02'], diff --git a/src/server/config/__tests__/override.js b/src/server/config/__tests__/override.js index 18b3117dcbe56..055e09d2f0f9f 100644 --- a/src/server/config/__tests__/override.js +++ b/src/server/config/__tests__/override.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; describe('override(target, source)', function () { it('should override the values form source to target', function () { - let target = { + const target = { test: { enable: true, host: ['host-01', 'host-02'], @@ -13,7 +13,7 @@ describe('override(target, source)', function () { } } }; - let source = { test: { client: { type: 'nosql' } } }; + const source = { test: { client: { type: 'nosql' } } }; expect(override(target, source)).to.eql({ test: { enable: true, diff --git a/src/server/config/complete.js b/src/server/config/complete.js index be44448733782..1018ccc496b68 100644 --- a/src/server/config/complete.js +++ b/src/server/config/complete.js @@ -4,7 +4,7 @@ export default function (kbnServer, server, config) { return kbnServer.config; }); - let tmpl = 'Settings for "<%= key %>" were not applied, check for spelling errors and ensure the plugin is loaded.'; + const tmpl = 'Settings for "<%= key %>" were not applied, check for spelling errors and ensure the plugin is loaded.'; for (let [key, val] of config.getPendingSets()) { server.log(['warning', 'config'], { key, val, tmpl }); } diff --git a/src/server/config/config.js b/src/server/config/config.js index 28c8ea4158138..db6b3520b776c 100644 --- a/src/server/config/config.js +++ b/src/server/config/config.js @@ -42,7 +42,7 @@ module.exports = class Config { _.set(this[schemaExts], key, extension); this[schema] = null; - let initialVals = _.get(this[pendingSets], key); + const initialVals = _.get(this[pendingSets], key); if (initialVals) { this.set(key, initialVals); unset(this[pendingSets], key); @@ -86,11 +86,11 @@ module.exports = class Config { if (_.isObject(env)) env = env.name; if (!env) env = process.env.NODE_ENV || 'production'; - let dev = env === 'development'; - let prod = env === 'production'; + const dev = env === 'development'; + const prod = env === 'production'; // pass the environment as context so that it can be refed in config - let context = { + const context = { env: env, prod: prod, dev: dev, @@ -107,7 +107,7 @@ module.exports = class Config { ); } - let results = Joi.validate(newVals, this.getSchema(), { context }); + const results = Joi.validate(newVals, this.getSchema(), { context }); if (results.error) { throw results.error; @@ -121,7 +121,7 @@ module.exports = class Config { return clone(this[vals]); } - let value = _.get(this[vals], key); + const value = _.get(this[vals], key); if (value === undefined) { if (!this.has(key)) { throw new Error('Unknown config key: ' + key); @@ -138,7 +138,7 @@ module.exports = class Config { // Only go deep on inner objects with children if (_.size(schema._inner.children)) { for (let i = 0; i < schema._inner.children.length; i++) { - let child = schema._inner.children[i]; + const child = schema._inner.children[i]; // If the child is an object recurse through it's children and return // true if there's a match if (child.schema._type === 'object') { diff --git a/src/server/config/explode_by.js b/src/server/config/explode_by.js index 50e2b2e82615f..a2e632ddf2a68 100644 --- a/src/server/config/explode_by.js +++ b/src/server/config/explode_by.js @@ -1,10 +1,10 @@ import _ from 'lodash'; module.exports = function (dot, flatObject) { - let fullObject = {}; + const fullObject = {}; _.each(flatObject, function (value, key) { - let keys = key.split(dot); + const keys = key.split(dot); (function walk(memo, keys, value) { - let _key = keys.shift(); + const _key = keys.shift(); if (keys.length === 0) { memo[_key] = value; } else { diff --git a/src/server/config/flatten_with.js b/src/server/config/flatten_with.js index 1401e12f0fb85..ede084f56a3fc 100644 --- a/src/server/config/flatten_with.js +++ b/src/server/config/flatten_with.js @@ -1,7 +1,7 @@ import _ from 'lodash'; module.exports = function (dot, nestedObj, flattenArrays) { - let stack = []; // track key stack - let flatObj = {}; + const stack = []; // track key stack + const flatObj = {}; (function flattenObj(obj) { _.keys(obj).forEach(function (key) { stack.push(key); diff --git a/src/server/config/override.js b/src/server/config/override.js index ef850a32754ae..3354fd5956fe7 100644 --- a/src/server/config/override.js +++ b/src/server/config/override.js @@ -3,8 +3,8 @@ import flattenWith from './flatten_with'; import explodeBy from './explode_by'; module.exports = function (target, source) { - let _target = flattenWith('.', target); - let _source = flattenWith('.', source); + const _target = flattenWith('.', target); + const _source = flattenWith('.', source); return explodeBy('.', _.defaults(_source, _target)); }; diff --git a/src/server/http/index.js b/src/server/http/index.js index 2f84533923d9d..621ecdd6192bc 100644 --- a/src/server/http/index.js +++ b/src/server/http/index.js @@ -71,7 +71,7 @@ module.exports = async function (kbnServer, server, config) { // attach the app name to the server, so we can be sure we are actually talking to kibana server.ext('onPreResponse', function (req, reply) { - let response = req.response; + const response = req.response; if (response.isBoom) { response.output.headers['kbn-name'] = kbnServer.name; @@ -99,7 +99,7 @@ module.exports = async function (kbnServer, server, config) { method: 'GET', path: '/{p*}', handler: function (req, reply) { - let path = req.path; + const path = req.path; if (path === '/' || path.charAt(path.length - 1) !== '/') { return reply(Boom.notFound()); } diff --git a/src/server/kbn_server.js b/src/server/kbn_server.js index dd4088c0b4421..a84968fa317a8 100644 --- a/src/server/kbn_server.js +++ b/src/server/kbn_server.js @@ -5,7 +5,7 @@ import { fromRoot, pkg } from '../utils'; import Config from './config/config'; import loggingConfiguration from './logging/configuration'; -let rootDir = fromRoot('.'); +const rootDir = fromRoot('.'); module.exports = class KbnServer { constructor(settings) { @@ -72,7 +72,7 @@ module.exports = class KbnServer { * @return {Promise} - promise that is resolved when the final mixin completes. */ async mixin(...fns) { - for (let fn of compact(flatten(fns))) { + for (const fn of compact(flatten(fns))) { await fn.call(this, this, this.server, this.config); } } diff --git a/src/server/logging/__tests__/apply_filters_to_keys.js b/src/server/logging/__tests__/apply_filters_to_keys.js index 0175b90ff221b..02c3efab19b43 100644 --- a/src/server/logging/__tests__/apply_filters_to_keys.js +++ b/src/server/logging/__tests__/apply_filters_to_keys.js @@ -3,7 +3,7 @@ import expect from 'expect.js'; describe('applyFiltersToKeys(obj, actionsByKey)', function () { it('applies for each key+prop in actionsByKey', function () { - let data = applyFiltersToKeys({ + const data = applyFiltersToKeys({ a: { b: { c: 1 diff --git a/src/server/logging/apply_filters_to_keys.js b/src/server/logging/apply_filters_to_keys.js index bc85f2fd1f555..19dc6e5d154d8 100644 --- a/src/server/logging/apply_filters_to_keys.js +++ b/src/server/logging/apply_filters_to_keys.js @@ -7,7 +7,7 @@ function replacer(match, group) { } function apply(obj, key, action) { - for (let k in obj) { + for (const k in obj) { if (obj.hasOwnProperty(k)) { let val = obj[k]; if (k === key) { @@ -21,9 +21,9 @@ function apply(obj, key, action) { obj[k] = ('' + val).replace(/./g, 'X'); } else if (/\/.+\//.test(action)) { - let matches = action.match(/\/(.+)\//); + const matches = action.match(/\/(.+)\//); if (matches) { - let regex = new RegExp(matches[1]); + const regex = new RegExp(matches[1]); obj[k] = ('' + val).replace(regex, replacer); } } diff --git a/src/server/logging/configuration.js b/src/server/logging/configuration.js index 2a894a0d97e44..be66a2e738c8b 100644 --- a/src/server/logging/configuration.js +++ b/src/server/logging/configuration.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import logReporter from './log_reporter'; export default function loggingConfiguration(config) { - let events = config.get('logging.events'); + const events = config.get('logging.events'); if (config.get('logging.silent')) { _.defaults(events, {}); diff --git a/src/server/logging/log_format.js b/src/server/logging/log_format.js index 7d11c59abd265..7a077ecdd5c27 100644 --- a/src/server/logging/log_format.js +++ b/src/server/logging/log_format.js @@ -18,7 +18,7 @@ function serializeError(err) { }; } -let levelColor = function (code) { +const levelColor = function (code) { if (code < 299) return ansicolors.green(code); if (code < 399) return ansicolors.yellow(code); if (code < 499) return ansicolors.magenta(code); @@ -41,13 +41,13 @@ module.exports = class TransformObjStream extends Stream.Transform { } _transform(event, enc, next) { - let data = this.filter(this.readEvent(event)); + const data = this.filter(this.readEvent(event)); this.push(this.format(data) + '\n'); next(); } readEvent(event) { - let data = { + const data = { type: event.event, '@timestamp': moment.utc(event.timestamp).format(), tags: [].concat(event.tags || []), @@ -82,7 +82,7 @@ module.exports = class TransformObjStream extends Stream.Transform { contentLength: contentLength }; - let query = querystring.stringify(event.query); + const query = querystring.stringify(event.query); if (query) data.req.url += '?' + query; diff --git a/src/server/logging/log_format_json.js b/src/server/logging/log_format_json.js index 7df528ab968bb..440982bbd3ea7 100644 --- a/src/server/logging/log_format_json.js +++ b/src/server/logging/log_format_json.js @@ -1,7 +1,7 @@ import LogFormat from './log_format'; import stringify from 'json-stringify-safe'; -let stripColors = function (string) { +const stripColors = function (string) { return string.replace(/\u001b[^m]+m/g, ''); }; diff --git a/src/server/logging/log_format_string.js b/src/server/logging/log_format_string.js index ea1c2f3b4b3d3..ab8154995702c 100644 --- a/src/server/logging/log_format_string.js +++ b/src/server/logging/log_format_string.js @@ -4,7 +4,7 @@ import moment from 'moment'; import LogFormat from './log_format'; -let statuses = [ +const statuses = [ 'err', 'info', 'error', @@ -14,7 +14,7 @@ let statuses = [ 'debug' ]; -let typeColors = { +const typeColors = { log: 'blue', req: 'green', res: 'green', @@ -34,22 +34,22 @@ let typeColors = { listening: 'magenta' }; -let color = _.memoize(function (name) { +const color = _.memoize(function (name) { return ansicolors[typeColors[name]] || _.identity; }); -let type = _.memoize(function (t) { +const type = _.memoize(function (t) { return color(t)(_.pad(t, 7).slice(0, 7)); }); -let workerType = process.env.kbnWorkerType ? `${type(process.env.kbnWorkerType)} ` : ''; +const workerType = process.env.kbnWorkerType ? `${type(process.env.kbnWorkerType)} ` : ''; module.exports = class KbnLoggerJsonFormat extends LogFormat { format(data) { - let time = color('time')(moment(data.timestamp).utc().format('HH:mm:ss.SSS')); - let msg = data.error ? color('error')(data.error.stack) : color('message')(data.message); + const time = color('time')(moment(data.timestamp).utc().format('HH:mm:ss.SSS')); + const msg = data.error ? color('error')(data.error.stack) : color('message')(data.message); - let tags = _(data.tags) + const tags = _(data.tags) .sortBy(function (tag) { if (color(tag) === _.identity) return `2${tag}`; if (_.includes(statuses, tag)) return `0${tag}`; diff --git a/src/server/pid/index.js b/src/server/pid/index.js index 7d7c1dbdea0fb..a2dc452480e09 100644 --- a/src/server/pid/index.js +++ b/src/server/pid/index.js @@ -2,19 +2,19 @@ import _ from 'lodash'; import Boom from 'boom'; import Promise from 'bluebird'; import { unlinkSync as unlink } from 'fs'; -let writeFile = Promise.promisify(require('fs').writeFile); +const writeFile = Promise.promisify(require('fs').writeFile); module.exports = Promise.method(function (kbnServer, server, config) { - let path = config.get('pid.file'); + const path = config.get('pid.file'); if (!path) return; - let pid = String(process.pid); + const pid = String(process.pid); return writeFile(path, pid, { flag: 'wx' }) .catch(function (err) { if (err.code !== 'EEXIST') throw err; - let log = { + const log = { tmpl: 'pid file already exists at <%= path %>', path: path, pid: pid @@ -36,7 +36,7 @@ module.exports = Promise.method(function (kbnServer, server, config) { pid: pid }); - let clean = _.once(function (code) { + const clean = _.once(function (code) { unlink(path); }); diff --git a/src/server/plugins/check_enabled.js b/src/server/plugins/check_enabled.js index 7953165d88007..846716ad37477 100644 --- a/src/server/plugins/check_enabled.js +++ b/src/server/plugins/check_enabled.js @@ -3,7 +3,7 @@ import toPath from 'lodash/internal/toPath'; export default async function (kbnServer, server, config) { const { plugins } = kbnServer; - for (let plugin of plugins) { + for (const plugin of plugins) { const enabledInConfig = config.get([...toPath(plugin.configPrefix), 'enabled']); if (!enabledInConfig) { diff --git a/src/server/plugins/check_version.js b/src/server/plugins/check_version.js index bb50b8daac06f..edd6f27b4f04f 100644 --- a/src/server/plugins/check_version.js +++ b/src/server/plugins/check_version.js @@ -17,7 +17,7 @@ export default async function (kbnServer, server, config) { const warningMessages = new Set(); const plugins = kbnServer.plugins; - for (let plugin of plugins) { + for (const plugin of plugins) { const version = plugin.kibanaVersion; const name = get(plugin, 'pkg.name'); @@ -28,7 +28,7 @@ export default async function (kbnServer, server, config) { } } - for (let message of warningMessages) { + for (const message of warningMessages) { server.log(['warning'], message); } diff --git a/src/server/plugins/initialize.js b/src/server/plugins/initialize.js index 402b750fbcc03..262c2a9d0b6d2 100644 --- a/src/server/plugins/initialize.js +++ b/src/server/plugins/initialize.js @@ -7,7 +7,7 @@ module.exports = async function (kbnServer, server, config) { return []; } - let { plugins } = kbnServer; + const { plugins } = kbnServer; // extend plugin apis with additional context plugins.getPluginApis().forEach(api => { diff --git a/src/server/plugins/plugin.js b/src/server/plugins/plugin.js index 976cf41e3b216..da2d62a5b1e34 100644 --- a/src/server/plugins/plugin.js +++ b/src/server/plugins/plugin.js @@ -95,7 +95,7 @@ module.exports = class Plugin { } async getConfigSchema() { - let schema = await this.getExternalConfigSchema(Joi); + const schema = await this.getExternalConfigSchema(Joi); return schema || defaultConfigSchema; } @@ -105,7 +105,7 @@ module.exports = class Plugin { async init() { let { id, version, kbnServer, configPrefix } = this; - let { config } = kbnServer; + const { config } = kbnServer; // setup the hapi register function and get on with it const asyncRegister = async (server, options) => { diff --git a/src/server/plugins/plugin_collection.js b/src/server/plugins/plugin_collection.js index 62fdd3e90d786..2bddd6dc4bb25 100644 --- a/src/server/plugins/plugin_collection.js +++ b/src/server/plugins/plugin_collection.js @@ -5,17 +5,17 @@ import { get, indexBy } from 'lodash'; import toPath from 'lodash/internal/toPath'; import Collection from '../../utils/collection'; -let byIdCache = Symbol('byIdCache'); -let pluginApis = Symbol('pluginApis'); +const byIdCache = Symbol('byIdCache'); +const pluginApis = Symbol('pluginApis'); async function addPluginConfig(pluginCollection, plugin) { const configSchema = await plugin.getConfigSchema(); - let { config } = pluginCollection.kbnServer; + const { config } = pluginCollection.kbnServer; config.extendSchema(plugin.configPrefix, configSchema); } function removePluginConfig(pluginCollection, plugin) { - let { config } = pluginCollection.kbnServer; + const { config } = pluginCollection.kbnServer; config.removeSchema(plugin.configPrefix); } @@ -28,18 +28,18 @@ module.exports = class Plugins extends Collection { } async new(path) { - let api = new PluginApi(this.kbnServer, path); + const api = new PluginApi(this.kbnServer, path); this[pluginApis].add(api); - let output = [].concat(require(path)(api) || []); - let config = this.kbnServer.config; + const output = [].concat(require(path)(api) || []); + const config = this.kbnServer.config; if (!output.length) return; // clear the byIdCache this[byIdCache] = null; - for (let plugin of output) { + for (const plugin of output) { if (!plugin instanceof api.Plugin) { throw new TypeError('unexpected plugin export ' + inspect(plugin)); } diff --git a/src/server/plugins/plugin_init.js b/src/server/plugins/plugin_init.js index 8f5e9e3184478..7823b4669f42e 100644 --- a/src/server/plugins/plugin_init.js +++ b/src/server/plugins/plugin_init.js @@ -1,10 +1,10 @@ import { includes } from 'lodash'; export default async (plugins) => { - let path = []; + const path = []; const initialize = async function (id, fn) { - let plugin = plugins.byId[id]; + const plugin = plugins.byId[id]; if (includes(path, id)) { throw new Error(`circular dependencies found: "${path.concat(id).join(' -> ')}"`); @@ -12,7 +12,7 @@ export default async (plugins) => { path.push(id); - for (let reqId of plugin.requiredIds) { + for (const reqId of plugin.requiredIds) { if (!plugins.byId[reqId]) { throw new Error(`Unmet requirement "${reqId}" for plugin "${id}"`); } @@ -25,11 +25,11 @@ export default async (plugins) => { }; const collection = plugins.toArray(); - for (let {id} of collection) { + for (const {id} of collection) { await initialize(id, 'preInit'); } - for (let {id} of collection) { + for (const {id} of collection) { await initialize(id, 'init'); } }; diff --git a/src/server/plugins/scan.js b/src/server/plugins/scan.js index baa5147e44530..4ac6b3e5563ff 100644 --- a/src/server/plugins/scan.js +++ b/src/server/plugins/scan.js @@ -6,13 +6,13 @@ import { each } from 'bluebird'; import PluginCollection from './plugin_collection'; module.exports = async (kbnServer, server, config) => { - let plugins = kbnServer.plugins = new PluginCollection(kbnServer); + const plugins = kbnServer.plugins = new PluginCollection(kbnServer); - let scanDirs = [].concat(config.get('plugins.scanDirs') || []); - let pluginPaths = [].concat(config.get('plugins.paths') || []); + const scanDirs = [].concat(config.get('plugins.scanDirs') || []); + const pluginPaths = [].concat(config.get('plugins.paths') || []); - let debug = _.bindKey(server, 'log', ['plugins', 'debug']); - let warning = _.bindKey(server, 'log', ['plugins', 'warning']); + const debug = _.bindKey(server, 'log', ['plugins', 'debug']); + const warning = _.bindKey(server, 'log', ['plugins', 'warning']); // scan all scanDirs to find pluginPaths await each(scanDirs, async dir => { @@ -36,15 +36,15 @@ module.exports = async (kbnServer, server, config) => { await each(filenames, async name => { if (name[0] === '.') return; - let path = resolve(dir, name); - let stats = await fromNode(cb => stat(path, cb)); + const path = resolve(dir, name); + const stats = await fromNode(cb => stat(path, cb)); if (stats.isDirectory()) { pluginPaths.push(path); } }); }); - for (let path of pluginPaths) { + for (const path of pluginPaths) { let modulePath; try { modulePath = require.resolve(path); diff --git a/src/server/status/__tests__/server_status.js b/src/server/status/__tests__/server_status.js index 3d08250fbf81f..a1379d9373eaf 100644 --- a/src/server/status/__tests__/server_status.js +++ b/src/server/status/__tests__/server_status.js @@ -26,7 +26,7 @@ describe('ServerStatus class', function () { describe('#createForPlugin(plugin)', function () { it('should create a new status by plugin', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); expect(status).to.be.a(Status); }); }); @@ -45,7 +45,7 @@ describe('ServerStatus class', function () { describe('#getForPluginId(plugin)', function () { it('exposes plugin status for the plugin', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); expect(serverStatus.getForPluginId(plugin.id)).to.be(status); }); @@ -57,7 +57,7 @@ describe('ServerStatus class', function () { describe('#getState(id)', function () { it('should expose the state of a status by id', function () { - let status = serverStatus.create('someid'); + const status = serverStatus.create('someid'); status.green(); expect(serverStatus.getState('someid')).to.be('green'); }); @@ -65,7 +65,7 @@ describe('ServerStatus class', function () { describe('#getStateForPluginId(plugin)', function () { it('should expose the state of a plugin by id', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); status.green(); expect(serverStatus.getStateForPluginId(plugin.id)).to.be('green'); }); @@ -73,11 +73,11 @@ describe('ServerStatus class', function () { describe('#overall()', function () { it('considers each status to produce a summary', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); expect(serverStatus.overall().state).to.be('uninitialized'); - let match = function (overall, state) { + const match = function (overall, state) { expect(overall).to.have.property('state', state.id); expect(overall).to.have.property('title', state.title); expect(overall).to.have.property('icon', state.icon); @@ -102,15 +102,15 @@ describe('ServerStatus class', function () { const pluginOne = {id: 'one', version: '1.0.0'}; const pluginTwo = {id: 'two', version: '2.0.0'}; - let service = serverStatus.create('some service'); - let p1 = serverStatus.createForPlugin(pluginOne); - let p2 = serverStatus.createForPlugin(pluginTwo); + const service = serverStatus.create('some service'); + const p1 = serverStatus.createForPlugin(pluginOne); + const p2 = serverStatus.createForPlugin(pluginTwo); service.green(); p1.yellow(); p2.red(); - let json = JSON.parse(JSON.stringify(serverStatus)); + const json = JSON.parse(JSON.stringify(serverStatus)); expect(json).to.have.property('overall'); expect(json.overall.state).to.eql(serverStatus.overall().state); expect(json.statuses).to.have.length(3); diff --git a/src/server/status/__tests__/status.js b/src/server/status/__tests__/status.js index 2dfe037791027..810a84cabe30e 100644 --- a/src/server/status/__tests__/status.js +++ b/src/server/status/__tests__/status.js @@ -19,7 +19,7 @@ describe('Status class', function () { }); it('emits change when the status is set', function (done) { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); status.once('change', function (prevState, prevMsg, newState, newMsg) { expect(newState).to.be('green'); @@ -42,8 +42,8 @@ describe('Status class', function () { }); it('should only trigger the change listener when something changes', function () { - let status = serverStatus.createForPlugin(plugin); - let stub = sinon.stub(); + const status = serverStatus.createForPlugin(plugin); + const stub = sinon.stub(); status.on('change', stub); status.green('Ready'); status.green('Ready'); @@ -52,18 +52,18 @@ describe('Status class', function () { }); it('should create a JSON representation of the status', function () { - let status = serverStatus.createForPlugin(plugin); + const status = serverStatus.createForPlugin(plugin); status.green('Ready'); - let json = status.toJSON(); + const json = status.toJSON(); expect(json.id).to.eql(status.id); expect(json.state).to.eql('green'); expect(json.message).to.eql('Ready'); }); it('should call on handler if status is already matched', function (done) { - let status = serverStatus.createForPlugin(plugin); - let msg = 'Test Ready'; + const status = serverStatus.createForPlugin(plugin); + const msg = 'Test Ready'; status.green(msg); status.on('green', function (prev, prevMsg) { @@ -76,8 +76,8 @@ describe('Status class', function () { }); it('should call once handler if status is already matched', function (done) { - let status = serverStatus.createForPlugin(plugin); - let msg = 'Test Ready'; + const status = serverStatus.createForPlugin(plugin); + const msg = 'Test Ready'; status.green(msg); status.once('green', function (prev, prevMsg) { @@ -91,16 +91,16 @@ describe('Status class', function () { function testState(color) { it(`should change the state to ${color} when #${color}() is called`, function () { - let status = serverStatus.createForPlugin(plugin); - let message = 'testing ' + color; + const status = serverStatus.createForPlugin(plugin); + const message = 'testing ' + color; status[color](message); expect(status).to.have.property('state', color); expect(status).to.have.property('message', message); }); it(`should trigger the "change" listner when #${color}() is called`, function (done) { - let status = serverStatus.createForPlugin(plugin); - let message = 'testing ' + color; + const status = serverStatus.createForPlugin(plugin); + const message = 'testing ' + color; status.on('change', function (prev, prevMsg) { expect(status.state).to.be(color); expect(status.message).to.be(message); @@ -113,8 +113,8 @@ describe('Status class', function () { }); it(`should trigger the "${color}" listner when #${color}() is called`, function (done) { - let status = serverStatus.createForPlugin(plugin); - let message = 'testing ' + color; + const status = serverStatus.createForPlugin(plugin); + const message = 'testing ' + color; status.on(color, function (prev, prevMsg) { expect(status.state).to.be(color); expect(status.message).to.be(message); diff --git a/src/server/status/metrics.js b/src/server/status/metrics.js index 28b99011bc988..d00a8eb540d04 100644 --- a/src/server/status/metrics.js +++ b/src/server/status/metrics.js @@ -6,13 +6,13 @@ module.exports = function (kbnServer, server, config) { kbnServer.metrics = new Samples(12); server.plugins['even-better'].monitor.on('ops', function (event) { - let now = Date.now(); - let secSinceLast = (now - lastReport) / 1000; + const now = Date.now(); + const secSinceLast = (now - lastReport) / 1000; lastReport = now; - let port = config.get('server.port'); - let requests = _.get(event, ['requests', port, 'total'], 0); - let requestsPerSecond = requests / secSinceLast; + const port = config.get('server.port'); + const requests = _.get(event, ['requests', port, 'total'], 0); + const requestsPerSecond = requests / secSinceLast; kbnServer.metrics.add({ heapTotal: _.get(event, 'psmem.heapTotal'), diff --git a/src/server/status/samples.js b/src/server/status/samples.js index fd2bc4aa27c84..20164c07b7834 100644 --- a/src/server/status/samples.js +++ b/src/server/status/samples.js @@ -7,8 +7,8 @@ function Samples(max) { } Samples.prototype.add = function (sample) { - let vals = this.vals; - let length = this.length = Math.min(this.length + 1, this.max); + const vals = this.vals; + const length = this.length = Math.min(this.length + 1, this.max); _.forOwn(sample, function (val, name) { if (val == null) val = null; diff --git a/src/server/status/server_status.js b/src/server/status/server_status.js index 88c44354f2e71..ac9b4fa855e2e 100644 --- a/src/server/status/server_status.js +++ b/src/server/status/server_status.js @@ -24,7 +24,7 @@ module.exports = class ServerStatus { } each(fn) { - let self = this; + const self = this; _.forOwn(self._created, function (status, i, list) { if (status.state !== 'disabled') { fn.call(self, status, i, list); @@ -55,15 +55,15 @@ module.exports = class ServerStatus { } overall() { - let state = _(this._created) + const state = _(this._created) .map(function (status) { return states.get(status.state); }) .sortBy('severity') .pop(); - let statuses = _.where(this._created, { state: state.id }); - let since = _.get(_.sortBy(statuses, 'since'), [0, 'since']); + const statuses = _.where(this._created, { state: state.id }); + const since = _.get(_.sortBy(statuses, 'since'), [0, 'since']); return { state: state.id, @@ -83,7 +83,7 @@ module.exports = class ServerStatus { } toString() { - let overall = this.overall(); + const overall = this.overall(); return `${overall.title} – ${overall.nickname}`; } diff --git a/src/server/status/status.js b/src/server/status/status.js index 573eb041a2a6b..f8848f680b50c 100644 --- a/src/server/status/status.js +++ b/src/server/status/status.js @@ -65,8 +65,8 @@ states.all.forEach(function (state) { Status.prototype[state.id] = function (message) { if (this.state === 'disabled') return; - let previous = this.state; - let previousMsg = this.message; + const previous = this.state; + const previousMsg = this.message; this.error = null; this.message = message || state.title; diff --git a/src/test_utils/simulate_keys.js b/src/test_utils/simulate_keys.js index 8282d8e5cc9e3..b9c55f92e35a7 100644 --- a/src/test_utils/simulate_keys.js +++ b/src/test_utils/simulate_keys.js @@ -2,8 +2,8 @@ import $ from 'jquery'; import _ from 'lodash'; import Promise from 'bluebird'; import keyMap from 'ui/utils/key_map'; -let reverseKeyMap = _.mapValues(_.invert(keyMap), _.ary(_.parseInt, 1)); -let KeyboardEvent = window.KeyboardEvent; +const reverseKeyMap = _.mapValues(_.invert(keyMap), _.ary(_.parseInt, 1)); +const KeyboardEvent = window.KeyboardEvent; /** * Simulate keyboard events in an element. This allows testing the way that @@ -35,7 +35,7 @@ let KeyboardEvent = window.KeyboardEvent; * @async */ export default function ($el, sequence) { - let modifierState = { + const modifierState = { ctrlKey: false, shiftKey: false, altKey: false, @@ -45,7 +45,7 @@ export default function ($el, sequence) { return doList(_.clone(sequence)); function setModifier(key, state) { - let name = key + 'Key'; + const name = key + 'Key'; if (modifierState.hasOwnProperty(name)) { modifierState[name] = !!state; } @@ -91,14 +91,14 @@ export default function ($el, sequence) { } function fire(type, key, repeat) { - let keyCode = reverseKeyMap[key]; + const keyCode = reverseKeyMap[key]; if (!keyCode) throw new TypeError('invalid key "' + key + '"'); if (type === 'keydown') setModifier(key, true); if (type === 'keyup') setModifier(key, false); - let $target = _.isFunction($el) ? $el() : $el; - let $event = new $.Event(type, _.defaults({ keyCode: keyCode }, modifierState)); + const $target = _.isFunction($el) ? $el() : $el; + const $event = new $.Event(type, _.defaults({ keyCode: keyCode }, modifierState)); $target.trigger($event); } }; diff --git a/src/test_utils/stub_index_pattern.js b/src/test_utils/stub_index_pattern.js index c3be4bcbd87e8..134295c434f7f 100644 --- a/src/test_utils/stub_index_pattern.js +++ b/src/test_utils/stub_index_pattern.js @@ -9,10 +9,10 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import IndexPatternsFlattenHitProvider from 'ui/index_patterns/_flatten_hit'; import IndexPatternsFieldProvider from 'ui/index_patterns/_field'; export default function (Private) { - let fieldFormats = Private(RegistryFieldFormatsProvider); - let flattenHit = Private(IndexPatternsFlattenHitProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); + const flattenHit = Private(IndexPatternsFlattenHitProvider); - let Field = Private(IndexPatternsFieldProvider); + const Field = Private(IndexPatternsFieldProvider); function StubIndexPattern(pattern, timeField, fields) { this.id = pattern; diff --git a/src/ui/__tests__/ui_exports.js b/src/ui/__tests__/ui_exports.js index e5f6996af5fee..dcc87ccacb0a5 100644 --- a/src/ui/__tests__/ui_exports.js +++ b/src/ui/__tests__/ui_exports.js @@ -7,7 +7,7 @@ import * as kbnTestServer from '../../../test/utils/kbn_server'; describe('UiExports', function () { describe('#find()', function () { it('finds exports based on the passed export names', function () { - let uiExports = new UiExports({}); + const uiExports = new UiExports({}); uiExports.aliases.foo = ['a', 'b', 'c']; uiExports.aliases.bar = ['d', 'e', 'f']; @@ -17,7 +17,7 @@ describe('UiExports', function () { }); it('allows query types that match nothing', function () { - let uiExports = new UiExports({}); + const uiExports = new UiExports({}); uiExports.aliases.foo = ['a', 'b', 'c']; expect(uiExports.find(['foo'])).to.eql(['a', 'b', 'c']); diff --git a/src/ui/index.js b/src/ui/index.js index 2edcea8a305ae..0b93fa10cc2cf 100644 --- a/src/ui/index.js +++ b/src/ui/index.js @@ -25,17 +25,17 @@ export default async (kbnServer, server, config) => { bundlerEnv.addContext('buildNum', config.get('pkg.buildNum')); uiExports.addConsumer(bundlerEnv); - for (let plugin of kbnServer.plugins) { + for (const plugin of kbnServer.plugins) { uiExports.consumePlugin(plugin); } const bundles = kbnServer.bundles = new UiBundleCollection(bundlerEnv, config.get('optimize.bundleFilter')); - for (let app of uiExports.getAllApps()) { + for (const app of uiExports.getAllApps()) { bundles.addApp(app); } - for (let gen of uiExports.getBundleProviders()) { + for (const gen of uiExports.getBundleProviders()) { const bundle = await gen(UiBundle, bundlerEnv, uiExports.getAllApps(), kbnServer.plugins); if (bundle) bundles.add(bundle); } diff --git a/src/ui/public/agg_response/geo_json/__tests__/geo_json.js b/src/ui/public/agg_response/geo_json/__tests__/geo_json.js index 94bb16a66cb98..0d7b18f02abea 100644 --- a/src/ui/public/agg_response/geo_json/__tests__/geo_json.js +++ b/src/ui/public/agg_response/geo_json/__tests__/geo_json.js @@ -17,8 +17,8 @@ describe('GeoJson Agg Response Converter', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { - let Vis = Private(VisProvider); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const Vis = Private(VisProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); esResponse = Private(FixturesAggRespGeohashGridProvider); tabify = Private(AggResponseTabifyTabifyProvider); @@ -60,8 +60,8 @@ describe('GeoJson Agg Response Converter', function () { describe('with table ' + JSON.stringify(tableOpts), function () { it('outputs a chart', function () { - let table = makeTable(); - let chart = makeSingleChart(table); + const table = makeTable(); + const chart = makeSingleChart(table); expect(chart).to.only.have.keys( 'title', 'tooltipFormatter', @@ -78,9 +78,9 @@ describe('GeoJson Agg Response Converter', function () { }); it('outputs geohash points as features in a feature collection', function () { - let table = makeTable(); - let chart = makeSingleChart(table); - let geoJson = chart.geoJson; + const table = makeTable(); + const chart = makeSingleChart(table); + const geoJson = chart.geoJson; expect(geoJson.type).to.be('FeatureCollection'); expect(geoJson.features).to.be.an('array'); @@ -88,8 +88,8 @@ describe('GeoJson Agg Response Converter', function () { }); it('exports a bunch of properties about the geo hash grid', function () { - let geoJson = makeGeoJson(); - let props = geoJson.properties; + const geoJson = makeGeoJson(); + const props = geoJson.properties; // props expect(props).to.be.an('object'); @@ -122,7 +122,7 @@ describe('GeoJson Agg Response Converter', function () { it('should be geoJson format', function () { table.rows.forEach(function (row, i) { - let feature = chart.geoJson.features[i]; + const feature = chart.geoJson.features[i]; expect(feature).to.have.property('geometry'); expect(feature.geometry).to.be.an('object'); expect(feature).to.have.property('properties'); @@ -132,7 +132,7 @@ describe('GeoJson Agg Response Converter', function () { it('should have valid geometry data', function () { table.rows.forEach(function (row, i) { - let geometry = chart.geoJson.features[i].geometry; + const geometry = chart.geoJson.features[i].geometry; expect(geometry.type).to.be('Point'); expect(geometry).to.have.property('coordinates'); expect(geometry.coordinates).to.be.an('array'); @@ -144,8 +144,8 @@ describe('GeoJson Agg Response Converter', function () { it('should have value properties data', function () { table.rows.forEach(function (row, i) { - let props = chart.geoJson.features[i].properties; - let keys = ['value', 'geohash', 'aggConfigResult', 'rectangle', 'center']; + const props = chart.geoJson.features[i].properties; + const keys = ['value', 'geohash', 'aggConfigResult', 'rectangle', 'center']; expect(props).to.be.an('object'); expect(props).to.only.have.keys(keys); expect(props.geohash).to.be.a('string'); @@ -155,15 +155,15 @@ describe('GeoJson Agg Response Converter', function () { it('should use latLng in properties and lngLat in geometry', function () { table.rows.forEach(function (row, i) { - let geometry = chart.geoJson.features[i].geometry; - let props = chart.geoJson.features[i].properties; + const geometry = chart.geoJson.features[i].geometry; + const props = chart.geoJson.features[i].properties; expect(props.center).to.eql(geometry.coordinates.slice(0).reverse()); }); }); it('should handle both AggConfig and non-AggConfig results', function () { table.rows.forEach(function (row, i) { - let props = chart.geoJson.features[i].properties; + const props = chart.geoJson.features[i].properties; if (tableOpts.asAggConfigResults) { expect(props.aggConfigResult).to.be(row[metricColI]); expect(props.value).to.be(row[metricColI].value); diff --git a/src/ui/public/agg_response/geo_json/_tooltip_formatter.js b/src/ui/public/agg_response/geo_json/_tooltip_formatter.js index f444d5b27d0d5..23db29ff6622d 100644 --- a/src/ui/public/agg_response/geo_json/_tooltip_formatter.js +++ b/src/ui/public/agg_response/geo_json/_tooltip_formatter.js @@ -3,19 +3,19 @@ import _ from 'lodash'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function TileMapTooltipFormatter($compile, $rootScope, Private) { - let fieldFormats = Private(RegistryFieldFormatsProvider); - let $tooltipScope = $rootScope.$new(); - let $el = $('
').html(require('ui/agg_response/geo_json/_tooltip.html')); + const fieldFormats = Private(RegistryFieldFormatsProvider); + const $tooltipScope = $rootScope.$new(); + const $el = $('
').html(require('ui/agg_response/geo_json/_tooltip.html')); $compile($el)($tooltipScope); return function tooltipFormatter(feature) { if (!feature) return ''; - let value = feature.properties.value; - let acr = feature.properties.aggConfigResult; - let vis = acr.aggConfig.vis; + const value = feature.properties.value; + const acr = feature.properties.aggConfigResult; + const vis = acr.aggConfig.vis; - let metricAgg = acr.aggConfig; + const metricAgg = acr.aggConfig; let geoFormat = _.get(vis.aggs, 'byTypeName.geohash_grid[0].format'); if (!geoFormat) geoFormat = fieldFormats.getDefaultInstance('geo_point'); diff --git a/src/ui/public/agg_response/geo_json/geo_json.js b/src/ui/public/agg_response/geo_json/geo_json.js index aac0fba222985..fe7018aee29a5 100644 --- a/src/ui/public/agg_response/geo_json/geo_json.js +++ b/src/ui/public/agg_response/geo_json/geo_json.js @@ -3,7 +3,7 @@ import rowsToFeatures from 'ui/agg_response/geo_json/rows_to_features'; import AggResponseGeoJsonTooltipFormatterProvider from 'ui/agg_response/geo_json/_tooltip_formatter'; export default function TileMapConverterFn(Private, timefilter, $compile, $rootScope) { - let tooltipFormatter = Private(AggResponseGeoJsonTooltipFormatterProvider); + const tooltipFormatter = Private(AggResponseGeoJsonTooltipFormatterProvider); return function (vis, table) { @@ -13,13 +13,13 @@ export default function TileMapConverterFn(Private, timefilter, $compile, $rootS }); } - let geoI = columnIndex('segment'); - let metricI = columnIndex('metric'); - let geoAgg = _.get(table.columns, [geoI, 'aggConfig']); - let metricAgg = _.get(table.columns, [metricI, 'aggConfig']); + const geoI = columnIndex('segment'); + const metricI = columnIndex('metric'); + const geoAgg = _.get(table.columns, [geoI, 'aggConfig']); + const metricAgg = _.get(table.columns, [metricI, 'aggConfig']); - let features = rowsToFeatures(table, geoI, metricI); - let values = features.map(function (feature) { + const features = rowsToFeatures(table, geoI, metricI); + const values = features.map(function (feature) { return feature.properties.value; }); diff --git a/src/ui/public/agg_response/geo_json/rows_to_features.js b/src/ui/public/agg_response/geo_json/rows_to_features.js index 634bfd26b5335..38e2757a50466 100644 --- a/src/ui/public/agg_response/geo_json/rows_to_features.js +++ b/src/ui/public/agg_response/geo_json/rows_to_features.js @@ -12,19 +12,19 @@ function unwrap(val) { function convertRowsToFeatures(table, geoI, metricI) { return _.transform(table.rows, function (features, row) { - let geohash = unwrap(row[geoI]); + const geohash = unwrap(row[geoI]); if (!geohash) return; // fetch latLn of northwest and southeast corners, and center point - let location = decodeGeoHash(geohash); + const location = decodeGeoHash(geohash); - let centerLatLng = [ + const centerLatLng = [ location.latitude[2], location.longitude[2] ]; // order is nw, ne, se, sw - let rectangle = [ + const rectangle = [ [location.latitude[0], location.longitude[0]], [location.latitude[0], location.longitude[1]], [location.latitude[1], location.longitude[1]], diff --git a/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js b/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js index a5e5555c81243..fcf91a9518d74 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/build_hierarchical_data.js @@ -35,7 +35,7 @@ describe('buildHierarchicalData', function () { let results; beforeEach(function () { - let id = 1; + const id = 1; vis = new Vis(indexPattern, { type: 'pie', aggs: [ @@ -48,7 +48,7 @@ describe('buildHierarchicalData', function () { }); it('should set the slices with one child to a consistent label', function () { - let checkLabel = 'Count'; + const checkLabel = 'Count'; expect(results).to.have.property('slices'); expect(results.slices).to.have.property('children'); expect(results.slices.children).to.have.length(1); @@ -68,7 +68,7 @@ describe('buildHierarchicalData', function () { it('should set the rows', function () { let id = 1; - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -79,13 +79,13 @@ describe('buildHierarchicalData', function () { }); // We need to set the aggs to a known value. _.each(vis.aggs, function (agg) { agg.id = 'agg_' + id++; }); - let results = buildHierarchicalData(vis, fixtures.threeTermBuckets); + const results = buildHierarchicalData(vis, fixtures.threeTermBuckets); expect(results).to.have.property('rows'); }); it('should set the columns', function () { let id = 1; - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -96,7 +96,7 @@ describe('buildHierarchicalData', function () { }); // We need to set the aggs to a known value. _.each(vis.aggs, function (agg) { agg.id = 'agg_' + id++; }); - let results = buildHierarchicalData(vis, fixtures.threeTermBuckets); + const results = buildHierarchicalData(vis, fixtures.threeTermBuckets); expect(results).to.have.property('columns'); }); @@ -281,7 +281,7 @@ describe('buildHierarchicalData', function () { }); it('should set the hits attribute for the results', function () { - let errCall = Notifier.prototype.error.getCall(0); + const errCall = Notifier.prototype.error.getCall(0); expect(errCall).to.be.ok(); expect(errCall.args[0]).to.contain('not supported'); diff --git a/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js b/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js index f8afc426647ac..6aa310e87aba5 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/collect_branch.js @@ -4,7 +4,7 @@ import collectBranch from 'ui/agg_response/hierarchical/_collect_branch'; import expect from 'expect.js'; describe('collectBranch()', function () { let results; - let convert = function (name) { + const convert = function (name) { return 'converted:' + name; }; diff --git a/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js b/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js index f42e4442c4fd1..0a99fd9142198 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/create_raw_data.js @@ -37,7 +37,7 @@ describe('buildHierarchicalData()', function () { { type: 'terms', schema: 'segment', params: { field: 'geo.src' }} ] }); - let buckets = arrayToLinkedList(vis.aggs.bySchemaGroup.buckets); + const buckets = arrayToLinkedList(vis.aggs.bySchemaGroup.buckets); // We need to set the aggs to a known value. _.each(vis.aggs, function (agg) { agg.id = 'agg_' + id++; }); results = createRawData(vis, fixtures.threeTermBuckets); @@ -48,7 +48,7 @@ describe('buildHierarchicalData()', function () { expect(results.columns).to.have.length(6); _.each(results.columns, function (column) { expect(column).to.have.property('aggConfig'); - let agg = column.aggConfig; + const agg = column.aggConfig; expect(column).to.have.property('categoryName', agg.schema.name); expect(column).to.have.property('id', agg.id); expect(column).to.have.property('aggType', agg.type); diff --git a/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js b/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js index 8d2a45c3a1f45..59c20a8e518df 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/extract_buckets.js @@ -7,14 +7,14 @@ describe('buildHierarchicalData()', function () { it('should normalize a bucket object into an array', function () { - let bucket = { + const bucket = { buckets: { foo: { doc_count: 1 }, bar: { doc_count: 2 } } }; - let buckets = extractBuckets(bucket); + const buckets = extractBuckets(bucket); expect(buckets).to.be.an(Array); expect(buckets).to.have.length(2); expect(buckets[0]).to.have.property('key', 'foo'); @@ -24,19 +24,19 @@ describe('buildHierarchicalData()', function () { }); it('should return an empty array for undefined buckets', function () { - let buckets = extractBuckets(); + const buckets = extractBuckets(); expect(buckets).to.be.an(Array); expect(buckets).to.have.length(0); }); it('should return the bucket array', function () { - let bucket = { + const bucket = { buckets: [ { key: 'foo', doc_count: 1 }, { key: 'bar', doc_count: 2 } ] }; - let buckets = extractBuckets(bucket); + const buckets = extractBuckets(bucket); expect(buckets).to.be.an(Array); expect(buckets).to.be(bucket.buckets); }); diff --git a/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js b/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js index 97adf8ea4073b..d927ef738f4d7 100644 --- a/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js +++ b/src/ui/public/agg_response/hierarchical/__tests__/transform_aggregation.js @@ -42,17 +42,17 @@ describe('buildHierarchicalData()', function () { }); it('relies on metricAgg#getValue() for the size of the children', function () { - let aggData = { + const aggData = { buckets: [ { key: 'foo' }, { key: 'bar' } ] }; - let football = {}; + const football = {}; fixture.metric.getValue = _.constant(football); - let children = transform(fixture.agg, fixture.metric, aggData); + const children = transform(fixture.agg, fixture.metric, aggData); expect(children).to.be.an(Array); expect(children).to.have.length(2); expect(children[0]).to.have.property('size', football); @@ -60,7 +60,7 @@ describe('buildHierarchicalData()', function () { }); it('should create two levels of metrics', function () { - let children = transform(fixture.agg, fixture.metric, fixture.aggData); + const children = transform(fixture.agg, fixture.metric, fixture.aggData); fixture.metric.getValue = function (b) { return b.doc_count; }; expect(children).to.be.an(Array); diff --git a/src/ui/public/agg_response/hierarchical/_build_split.js b/src/ui/public/agg_response/hierarchical/_build_split.js index f4eb0fdf764ab..4cb52e7418a45 100644 --- a/src/ui/public/agg_response/hierarchical/_build_split.js +++ b/src/ui/public/agg_response/hierarchical/_build_split.js @@ -1,10 +1,10 @@ import collectKeys from 'ui/agg_response/hierarchical/_collect_keys'; import AggResponseHierarchicalTransformAggregationProvider from 'ui/agg_response/hierarchical/_transform_aggregation'; export default function biuldSplitProvider(Private) { - let transformer = Private(AggResponseHierarchicalTransformAggregationProvider); + const transformer = Private(AggResponseHierarchicalTransformAggregationProvider); return function (agg, metric, aggData) { // Ceate the split structure - let split = { label: '', slices: { children: [] } }; + const split = { label: '', slices: { children: [] } }; // Transform the aggData into splits split.slices.children = transformer(agg, metric, aggData); diff --git a/src/ui/public/agg_response/hierarchical/_collect_branch.js b/src/ui/public/agg_response/hierarchical/_collect_branch.js index a8588f31d58ef..73d8c6a4462ba 100644 --- a/src/ui/public/agg_response/hierarchical/_collect_branch.js +++ b/src/ui/public/agg_response/hierarchical/_collect_branch.js @@ -2,13 +2,13 @@ export default function (leaf) { // walk up the branch for each parent function walk(item, memo) { // record the the depth - let depth = item.depth - 1; + const depth = item.depth - 1; // Using the aggConfig determine what the field name is. If the aggConfig // doesn't exist (which means it's an _all agg) then use the level for // the field name const { aggConfig } = item; - let field = (aggConfig && aggConfig.getFieldDisplayName()) + const field = (aggConfig && aggConfig.getFieldDisplayName()) || (aggConfig && aggConfig.label) || ('level ' + item.depth); diff --git a/src/ui/public/agg_response/hierarchical/_collect_keys.js b/src/ui/public/agg_response/hierarchical/_collect_keys.js index 1b9a542462c75..aa43871365ea6 100644 --- a/src/ui/public/agg_response/hierarchical/_collect_keys.js +++ b/src/ui/public/agg_response/hierarchical/_collect_keys.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function collectKeys(children) { - let nextChildren = _.pluck(children, 'children'); - let keys = _.pluck(children, 'name'); + const nextChildren = _.pluck(children, 'children'); + const keys = _.pluck(children, 'name'); return _(nextChildren) .map(collectKeys) .flattenDeep() diff --git a/src/ui/public/agg_response/hierarchical/_create_raw_data.js b/src/ui/public/agg_response/hierarchical/_create_raw_data.js index 93b9c1b519bfe..ccf9077b1994b 100644 --- a/src/ui/public/agg_response/hierarchical/_create_raw_data.js +++ b/src/ui/public/agg_response/hierarchical/_create_raw_data.js @@ -3,12 +3,12 @@ import extractBuckets from 'ui/agg_response/hierarchical/_extract_buckets'; export default function (vis, resp) { // Create the initial results structure - let results = { rows: [] }; + const results = { rows: [] }; // Create a reference to the buckets and metrics - let metrics = vis.aggs.bySchemaGroup.metrics; - let buckets = vis.aggs.bySchemaGroup.buckets; - let aggs = []; + const metrics = vis.aggs.bySchemaGroup.metrics; + const buckets = vis.aggs.bySchemaGroup.buckets; + const aggs = []; if (buckets) { _.each(buckets, function (bucket) { @@ -37,7 +37,7 @@ export default function (vis, resp) { // if there are no buckets then we need to just set the value and return if (!buckets) { - let value = resp.aggregations + const value = resp.aggregations && resp.aggregations[metrics[0].id] && resp.aggregations[metrics[0].id].value || resp.hits.total; @@ -60,7 +60,7 @@ export default function (vis, resp) { // iterate through all the buckets _.each(extractBuckets(data[agg.id], agg), function (bucket) { - let _record = _.flattenDeep([record, bucket.key]); + const _record = _.flattenDeep([record, bucket.key]); _.each(metrics, function (metric) { let value = bucket.doc_count; if (bucket[metric.id] && !_.isUndefined(bucket[metric.id].value)) { @@ -73,7 +73,7 @@ export default function (vis, resp) { // buckets. If it does then we need to keep on walking the tree. // This is where the recursion happens. if (agg._next) { - let nextBucket = bucket[agg._next.id]; + const nextBucket = bucket[agg._next.id]; if (nextBucket && nextBucket.buckets) { walkBuckets(agg._next, bucket, _record); } diff --git a/src/ui/public/agg_response/hierarchical/_extract_buckets.js b/src/ui/public/agg_response/hierarchical/_extract_buckets.js index e80f408664535..b496bece578aa 100644 --- a/src/ui/public/agg_response/hierarchical/_extract_buckets.js +++ b/src/ui/public/agg_response/hierarchical/_extract_buckets.js @@ -2,7 +2,7 @@ import _ from 'lodash'; export default function (bucket, agg) { if (bucket && _.isPlainObject(bucket.buckets)) { return _.map(bucket.buckets, function (value, key) { - let item = _.cloneDeep(value); + const item = _.cloneDeep(value); item.key = agg ? agg.getKey(value, key) : key; return item; }); diff --git a/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js b/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js index f4acab3927a57..113cf8259f4c7 100644 --- a/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js +++ b/src/ui/public/agg_response/hierarchical/_hierarchical_tooltip_formatter.js @@ -3,19 +3,19 @@ import $ from 'jquery'; import collectBranch from 'ui/agg_response/hierarchical/_collect_branch'; import numeral from 'numeral'; export default function HierarchicalTooltipFormaterProvider($rootScope, $compile, $sce) { - let $tooltip = $(require('ui/agg_response/hierarchical/_tooltip.html')); - let $tooltipScope = $rootScope.$new(); + const $tooltip = $(require('ui/agg_response/hierarchical/_tooltip.html')); + const $tooltipScope = $rootScope.$new(); $compile($tooltip)($tooltipScope); return function (columns) { return function (event) { - let datum = event.datum; + const datum = event.datum; // Collect the current leaf and parents into an array of values $tooltipScope.rows = collectBranch(datum); - let metricCol = $tooltipScope.metricCol = _.find(columns, { categoryName: 'metric' }); + const metricCol = $tooltipScope.metricCol = _.find(columns, { categoryName: 'metric' }); // Map those values to what the tooltipSource.rows format. _.forEachRight($tooltipScope.rows, function (row, i, rows) { diff --git a/src/ui/public/agg_response/hierarchical/_transform_aggregation.js b/src/ui/public/agg_response/hierarchical/_transform_aggregation.js index a176f2d3e0154..fda5791ab8559 100644 --- a/src/ui/public/agg_response/hierarchical/_transform_aggregation.js +++ b/src/ui/public/agg_response/hierarchical/_transform_aggregation.js @@ -4,14 +4,14 @@ import AggConfigResult from 'ui/vis/agg_config_result'; export default function transformAggregationProvider(Private) { return function transformAggregation(agg, metric, aggData, parent) { return _.map(extractBuckets(aggData, agg), function (bucket) { - let aggConfigResult = new AggConfigResult( + const aggConfigResult = new AggConfigResult( agg, parent && parent.aggConfigResult, metric.getValue(bucket), agg.getKey(bucket) ); - let branch = { + const branch = { name: agg.fieldFormatter()(bucket.key), size: aggConfigResult.value, aggConfig: agg, @@ -27,7 +27,7 @@ export default function transformAggregationProvider(Private) { // If the next bucket exists and it has children the we need to // transform it as well. This is where the recursion happens. if (agg._next) { - let nextBucket = bucket[agg._next.id]; + const nextBucket = bucket[agg._next.id]; if (nextBucket && nextBucket.buckets) { branch.children = transformAggregation(agg._next, metric, nextBucket, branch); } diff --git a/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js b/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js index a5cb53784c256..9c8c7a95e4314 100644 --- a/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js +++ b/src/ui/public/agg_response/hierarchical/build_hierarchical_data.js @@ -6,11 +6,11 @@ import AggConfigResult from 'ui/vis/agg_config_result'; import AggResponseHierarchicalBuildSplitProvider from 'ui/agg_response/hierarchical/_build_split'; import AggResponseHierarchicalHierarchicalTooltipFormatterProvider from 'ui/agg_response/hierarchical/_hierarchical_tooltip_formatter'; export default function buildHierarchicalDataProvider(Private, Notifier) { - let buildSplit = Private(AggResponseHierarchicalBuildSplitProvider); - let tooltipFormatter = Private(AggResponseHierarchicalHierarchicalTooltipFormatterProvider); + const buildSplit = Private(AggResponseHierarchicalBuildSplitProvider); + const tooltipFormatter = Private(AggResponseHierarchicalHierarchicalTooltipFormatterProvider); - let notify = new Notifier({ + const notify = new Notifier({ location: 'Pie chart response converter' }); @@ -21,19 +21,19 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { // Find the metric so it's easier to reference. // TODO: Change this to support multiple metrics. - let metric = vis.aggs.bySchemaGroup.metrics[0]; + const metric = vis.aggs.bySchemaGroup.metrics[0]; // Link each agg to the next agg. This will be // to identify the next bucket aggregation buckets = arrayToLinkedList(buckets); // Create the raw data to be used in the spy panel - let raw = createRawData(vis, resp); + const raw = createRawData(vis, resp); // If buckets is falsy then we should just return the aggs if (!buckets) { - let label = 'Count'; - let value = resp.aggregations + const label = 'Count'; + const value = resp.aggregations && resp.aggregations[metric.id] && resp.aggregations[metric.id].value || resp.hits.total; @@ -50,8 +50,8 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { }; } - let firstAgg = buckets[0]; - let aggData = resp.aggregations[firstAgg.id]; + const firstAgg = buckets[0]; + const aggData = resp.aggregations[firstAgg.id]; if (!firstAgg._next && firstAgg.schema.name === 'split') { notify.error('Splitting charts without splitting slices is not supported. Pretending that we are just splitting slices.'); @@ -59,7 +59,7 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { // start with splitting slices if (!firstAgg._next || firstAgg.schema.name === 'segment') { - let split = buildSplit(firstAgg, metric, aggData); + const split = buildSplit(firstAgg, metric, aggData); split.hits = resp.hits.total; split.raw = raw; split.tooltipFormatter = tooltipFormatter(raw.columns); @@ -67,17 +67,17 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { } // map the split aggregations into rows. - let rows = _.map(extractBuckets(aggData, firstAgg), function (bucket) { - let agg = firstAgg._next; - let split = buildSplit(agg, metric, bucket[agg.id]); + const rows = _.map(extractBuckets(aggData, firstAgg), function (bucket) { + const agg = firstAgg._next; + const split = buildSplit(agg, metric, bucket[agg.id]); // Since splits display labels we need to set it. split.label = firstAgg.fieldFormatter()(agg.getKey(bucket)); - let displayName = firstAgg.getFieldDisplayName(); + const displayName = firstAgg.getFieldDisplayName(); if (!_.isEmpty(displayName)) split.label += ': ' + displayName; split.tooltipFormatter = tooltipFormatter(raw.columns); - let aggConfigResult = new AggConfigResult(firstAgg, null, null, firstAgg.getKey(bucket)); + const aggConfigResult = new AggConfigResult(firstAgg, null, null, firstAgg.getKey(bucket)); split.split = { aggConfig: firstAgg, aggConfigResult: aggConfigResult, key: bucket.key }; _.each(split.slices.children, function (child) { child.aggConfigResult.$parent = aggConfigResult; @@ -85,7 +85,7 @@ export default function buildHierarchicalDataProvider(Private, Notifier) { return split; }); - let result = { hits: resp.hits.total, raw: raw }; + const result = { hits: resp.hits.total, raw: raw }; if (firstAgg.params.row) { result.rows = rows; } else { diff --git a/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js b/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js index 4e9c563f78dbf..c07780bfbf0a2 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js +++ b/src/ui/public/agg_response/point_series/__tests__/_add_to_siri.js @@ -10,9 +10,9 @@ describe('addToSiri', function () { })); it('creates a new series the first time it sees an id', function () { - let series = new Map(); - let point = {}; - let id = 'id'; + const series = new Map(); + const point = {}; + const id = 'id'; addToSiri(series, point, id); expect(series.has(id)).to.be(true); @@ -23,13 +23,13 @@ describe('addToSiri', function () { }); it('adds points to existing series if id has been seen', function () { - let series = new Map(); - let id = 'id'; + const series = new Map(); + const id = 'id'; - let point = {}; + const point = {}; addToSiri(series, point, id); - let point2 = {}; + const point2 = {}; addToSiri(series, point2, id); expect(series.has(id)).to.be(true); @@ -41,10 +41,10 @@ describe('addToSiri', function () { }); it('allows overriding the series label', function () { - let series = new Map(); - let id = 'id'; - let label = 'label'; - let point = {}; + const series = new Map(); + const id = 'id'; + const label = 'label'; + const point = {}; addToSiri(series, point, id, label); expect(series.has(id)).to.be(true); diff --git a/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js b/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js index 501631e1c921a..1b1661186b2be 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js +++ b/src/ui/public/agg_response/point_series/__tests__/_fake_x_aspect.js @@ -22,8 +22,8 @@ describe('makeFakeXAspect', function () { })); it('creates an object that looks like an aspect', function () { - let vis = new Vis(indexPattern, { type: 'histogram' }); - let aspect = makeFakeXAspect(vis); + const vis = new Vis(indexPattern, { type: 'histogram' }); + const aspect = makeFakeXAspect(vis); expect(aspect) .to.have.property('i', -1) diff --git a/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js b/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js index e1bf5ce07a702..ef4e7079c9e81 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js +++ b/src/ui/public/agg_response/point_series/__tests__/_get_aspects.js @@ -27,7 +27,7 @@ describe('getAspects', function () { let vis; let table; - let date = _.memoize(function (n) { + const date = _.memoize(function (n) { return moment().startOf('day').add(n, 'hour').valueOf(); }); @@ -50,7 +50,7 @@ describe('getAspects', function () { function init(group, x, y) { // map args to indicies that should be removed - let filter = filterByIndex([ + const filter = filterByIndex([ x > 0, x > 1, group > 0, @@ -92,7 +92,7 @@ describe('getAspects', function () { ].map(filter) }; - let aggs = vis.aggs.splice(0, vis.aggs.length); + const aggs = vis.aggs.splice(0, vis.aggs.length); filter(aggs).forEach(function (filter) { vis.aggs.push(filter); }); @@ -101,7 +101,7 @@ describe('getAspects', function () { it('produces an aspect object for each of the aspect types found in the columns', function () { init(1, 1, 1); - let aspects = getAspects(vis, table); + const aspects = getAspects(vis, table); validate(aspects.x, 0); validate(aspects.series, 1); validate(aspects.y, 2); @@ -110,7 +110,7 @@ describe('getAspects', function () { it('uses arrays only when there are more than one aspect of a specific type', function () { init(0, 1, 2); - let aspects = getAspects(vis, table); + const aspects = getAspects(vis, table); validate(aspects.x, 0); expect(aspects.series == null).to.be(true); @@ -139,7 +139,7 @@ describe('getAspects', function () { it('creates a fake x aspect if the column does not exist', function () { init(0, 0, 1); - let aspects = getAspects(vis, table); + const aspects = getAspects(vis, table); expect(aspects.x) .to.be.an('object') diff --git a/src/ui/public/agg_response/point_series/__tests__/_get_point.js b/src/ui/public/agg_response/point_series/__tests__/_get_point.js index 93462f6f50a71..ca5a11751f093 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_get_point.js +++ b/src/ui/public/agg_response/point_series/__tests__/_get_point.js @@ -7,8 +7,8 @@ describe('getPoint', function () { let getPoint; - let truthFormatted = { fieldFormatter: _.constant(_.constant(true)) }; - let identFormatted = { fieldFormatter: _.constant(_.identity) }; + const truthFormatted = { fieldFormatter: _.constant(_.constant(true)) }; + const identFormatted = { fieldFormatter: _.constant(_.identity) }; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { @@ -31,9 +31,9 @@ describe('getPoint', function () { }); it('properly unwraps and scales values', function () { - let row = [ { value: 1 }, { value: 2 }, { value: 3 } ]; - let zAspect = { i: 2 }; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect, zAspect); + const row = [ { value: 1 }, { value: 2 }, { value: 3 } ]; + const zAspect = { i: 2 }; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect, zAspect); expect(point) .to.have.property('x', 1) @@ -44,8 +44,8 @@ describe('getPoint', function () { }); it('ignores points with a y value of NaN', function () { - let row = [ { value: 1 }, { value: 'NaN' }]; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const row = [ { value: 1 }, { value: 'NaN' }]; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point).to.be(void 0); }); }); @@ -64,8 +64,8 @@ describe('getPoint', function () { }); it('properly unwraps and scales values', function () { - let seriesAspect = { i: 1, agg: identFormatted }; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const seriesAspect = { i: 1, agg: identFormatted }; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point) .to.have.property('x', 1) @@ -75,8 +75,8 @@ describe('getPoint', function () { }); it('properly formats series values', function () { - let seriesAspect = { i: 1, agg: truthFormatted }; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const seriesAspect = { i: 1, agg: truthFormatted }; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point) .to.have.property('x', 1) @@ -86,8 +86,8 @@ describe('getPoint', function () { }); it ('adds the aggConfig to the points', function () { - let seriesAspect = { i: 1, agg: truthFormatted}; - let point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); + const seriesAspect = { i: 1, agg: truthFormatted}; + const point = getPoint(xAspect, seriesAspect, yScale, row, yAspect); expect(point).to.have.property('aggConfig', truthFormatted); }); diff --git a/src/ui/public/agg_response/point_series/__tests__/_get_series.js b/src/ui/public/agg_response/point_series/__tests__/_get_series.js index fdaa7d7107071..5c1ac921ce870 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_get_series.js +++ b/src/ui/public/agg_response/point_series/__tests__/_get_series.js @@ -5,7 +5,7 @@ import AggResponsePointSeriesGetSeriesProvider from 'ui/agg_response/point_serie describe('getSeries', function () { let getSeries; - let agg = { fieldFormatter: _.constant(_.identity) }; + const agg = { fieldFormatter: _.constant(_.identity) }; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { @@ -19,7 +19,7 @@ describe('getSeries', function () { } it('produces a single series with points for each row', function () { - let rows = [ + const rows = [ [1, 2, 3], [1, 2, 3], [1, 2, 3], @@ -28,7 +28,7 @@ describe('getSeries', function () { ].map(wrapRows); const yCol = { aggConfig: {}, title: 'y' }; - let chart = { + const chart = { aspects: { x: { i: 0 }, y: { i: 1, col: yCol }, @@ -36,13 +36,13 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') .and.to.have.length(1); - let siri = series[0]; + const siri = series[0]; expect(siri) .to.be.an('object') .and.have.property('label', yCol.title) @@ -61,7 +61,7 @@ describe('getSeries', function () { }); it('produces multiple series if there are multiple y aspects', function () { - let rows = [ + const rows = [ [1, 2, 3], [1, 2, 3], [1, 2, 3], @@ -69,7 +69,7 @@ describe('getSeries', function () { [1, 2, 3] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: 0 }, y: [ @@ -79,7 +79,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') @@ -104,7 +104,7 @@ describe('getSeries', function () { }); it('produces multiple series if there is a series aspect', function () { - let rows = [ + const rows = [ ['0', 3], ['1', 3], ['1', 'NaN'], @@ -115,7 +115,7 @@ describe('getSeries', function () { ['1', 3] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: -1 }, series: { i: 0, agg: agg }, @@ -123,7 +123,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') @@ -148,7 +148,7 @@ describe('getSeries', function () { }); it('produces multiple series if there is a series aspect and multipl y aspects', function () { - let rows = [ + const rows = [ ['0', 3, 4], ['1', 3, 4], ['0', 3, 4], @@ -157,7 +157,7 @@ describe('getSeries', function () { ['1', 3, 4] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: -1 }, series: { i: 0, agg: agg }, @@ -168,7 +168,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series) .to.be.an('array') @@ -198,7 +198,7 @@ describe('getSeries', function () { }); it('produces a series list in the same order as its corresponding metric column', function () { - let rows = [ + const rows = [ ['0', 3, 4], ['1', 3, 4], ['0', 3, 4], @@ -207,7 +207,7 @@ describe('getSeries', function () { ['1', 3, 4] ].map(wrapRows); - let chart = { + const chart = { aspects: { x: { i: -1 }, series: { i: 0, agg: agg }, @@ -218,7 +218,7 @@ describe('getSeries', function () { } }; - let series = getSeries(rows, chart); + const series = getSeries(rows, chart); expect(series[0]).to.have.property('label', '0: 0'); expect(series[1]).to.have.property('label', '0: 1'); expect(series[2]).to.have.property('label', '1: 0'); @@ -231,7 +231,7 @@ describe('getSeries', function () { y.i = i; }); - let series2 = getSeries(rows, chart); + const series2 = getSeries(rows, chart); expect(series2[0]).to.have.property('label', '0: 1'); expect(series2[1]).to.have.property('label', '0: 0'); expect(series2[2]).to.have.property('label', '1: 1'); diff --git a/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js b/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js index 974afab294831..9c2cfb9ef0890 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js +++ b/src/ui/public/agg_response/point_series/__tests__/_init_x_axis.js @@ -11,7 +11,7 @@ describe('initXAxis', function () { initXAxis = Private(AggResponsePointSeriesInitXAxisProvider); })); - let baseChart = { + const baseChart = { aspects: { x: { agg: { @@ -27,7 +27,7 @@ describe('initXAxis', function () { }; it('sets the xAxisFormatter if the agg is not ordered', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); initXAxis(chart); expect(chart) .to.have.property('xAxisLabel', 'label') @@ -35,7 +35,7 @@ describe('initXAxis', function () { }); it('makes the chart ordered if the agg is ordered', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); chart.aspects.x.agg.type.ordered = true; initXAxis(chart); @@ -50,7 +50,7 @@ describe('initXAxis', function () { }); it('reads the interval param from the x agg', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); chart.aspects.x.agg.type.ordered = true; chart.aspects.x.agg.write = _.constant({ params: { interval: 10 } }); diff --git a/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js b/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js index 97f1c98e12487..f545e3db6e0f5 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js +++ b/src/ui/public/agg_response/point_series/__tests__/_init_y_axis.js @@ -19,7 +19,7 @@ describe('initYAxis', function () { }; } - let baseChart = { + const baseChart = { aspects: { y: [ { agg: agg(), col: { title: 'y1' } }, @@ -33,17 +33,17 @@ describe('initYAxis', function () { }; describe('with a single y aspect', function () { - let singleYBaseChart = _.cloneDeep(baseChart); + const singleYBaseChart = _.cloneDeep(baseChart); singleYBaseChart.aspects.y = singleYBaseChart.aspects.y[0]; it('sets the yAxisFormatter the the field formats convert fn', function () { - let chart = _.cloneDeep(singleYBaseChart); + const chart = _.cloneDeep(singleYBaseChart); initYAxis(chart); expect(chart).to.have.property('yAxisFormatter', chart.aspects.y.agg.fieldFormatter()); }); it('sets the yAxisLabel', function () { - let chart = _.cloneDeep(singleYBaseChart); + const chart = _.cloneDeep(singleYBaseChart); initYAxis(chart); expect(chart).to.have.property('yAxisLabel', 'y1'); }); @@ -51,7 +51,7 @@ describe('initYAxis', function () { describe('with mutliple y aspects', function () { it('sets the yAxisFormatter the the field formats convert fn for the first y aspect', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); initYAxis(chart); expect(chart).to.have.property('yAxisFormatter'); @@ -61,7 +61,7 @@ describe('initYAxis', function () { }); it('does not set the yAxisLabel, it does not make sense to put multiple labels on the same axis', function () { - let chart = _.cloneDeep(baseChart); + const chart = _.cloneDeep(baseChart); initYAxis(chart); expect(chart).to.have.property('yAxisLabel', ''); }); diff --git a/src/ui/public/agg_response/point_series/__tests__/_main.js b/src/ui/public/agg_response/point_series/__tests__/_main.js index 9d077175a77e7..ca902c578386c 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_main.js +++ b/src/ui/public/agg_response/point_series/__tests__/_main.js @@ -25,20 +25,20 @@ describe('pointSeriesChartDataFromTable', function () { })); it('handles a table with just a count', function () { - let vis = new Vis(indexPattern, { type: 'histogram' }); - let agg = vis.aggs[0]; - let result = new AggConfigResult(vis.aggs[0], void 0, 100, 100); + const vis = new Vis(indexPattern, { type: 'histogram' }); + const agg = vis.aggs[0]; + const result = new AggConfigResult(vis.aggs[0], void 0, 100, 100); - let table = new Table(); + const table = new Table(); table.columns = [ { aggConfig: agg } ]; table.rows.push([ result ]); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); expect(chartData.series).to.have.length(1); - let series = chartData.series[0]; + const series = chartData.series[0]; expect(series.values).to.have.length(1); expect(series.values[0]) .to.have.property('x', '_all') @@ -47,7 +47,7 @@ describe('pointSeriesChartDataFromTable', function () { }); it('handles a table with x and y column', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'count', schema: 'metric' }, @@ -55,32 +55,32 @@ describe('pointSeriesChartDataFromTable', function () { ] }); - let y = { + const y = { agg: vis.aggs[0], col: { aggConfig: vis.aggs[0], title: vis.aggs[0].makeLabel() }, at: function (i) { return 100 * i; } }; - let x = { + const x = { agg: vis.aggs[1], col: { aggConfig: vis.aggs[1] }, at: function (i) { return moment().startOf('day').add(i, 'day').valueOf(); } }; - let rowCount = 3; - let table = new Table(); + const rowCount = 3; + const table = new Table(); table.columns = [ x.col, y.col ]; _.times(rowCount, function (i) { - let date = new AggConfigResult(x.agg, void 0, x.at(i)); + const date = new AggConfigResult(x.agg, void 0, x.at(i)); table.rows.push([date, new AggConfigResult(y.agg, date, y.at(i))]); }); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); expect(chartData.series).to.have.length(1); - let series = chartData.series[0]; + const series = chartData.series[0]; expect(series).to.have.property('label', y.col.title); expect(series.values).to.have.length(rowCount); series.values.forEach(function (point, i) { @@ -101,7 +101,7 @@ describe('pointSeriesChartDataFromTable', function () { }); it('handles a table with an x and two y aspects', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -110,40 +110,40 @@ describe('pointSeriesChartDataFromTable', function () { ] }); - let avg = { + const avg = { agg: vis.aggs[0], col: { title: 'average', aggConfig: vis.aggs[0] }, at: function (i) { return 75.444 * (i + 1); } }; - let date = { + const date = { agg: vis.aggs[1], col: { title: 'date', aggConfig: vis.aggs[1] }, at: function (i) { return moment().startOf('day').add(i, 'day').valueOf(); } }; - let max = { + const max = { agg: vis.aggs[2], col: { title: 'maximum', aggConfig: vis.aggs[2] }, at: function (i) { return 100 * (i + 1); } }; - let rowCount = 3; - let table = new Table(); + const rowCount = 3; + const table = new Table(); table.columns = [ date.col, avg.col, max.col ]; _.times(rowCount, function (i) { - let dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); - let avgResult = new AggConfigResult(avg.agg, dateResult, avg.at(i)); - let maxResult = new AggConfigResult(max.agg, dateResult, max.at(i)); + const dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); + const avgResult = new AggConfigResult(avg.agg, dateResult, avg.at(i)); + const maxResult = new AggConfigResult(max.agg, dateResult, max.at(i)); table.rows.push([dateResult, avgResult, maxResult]); }); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); expect(chartData.series).to.have.length(2); chartData.series.forEach(function (siri, i) { - let metric = i === 0 ? avg : max; + const metric = i === 0 ? avg : max; expect(siri).to.have.property('label', metric.col.label); expect(siri.values).to.have.length(rowCount); @@ -170,7 +170,7 @@ describe('pointSeriesChartDataFromTable', function () { }); it('handles a table with an x, a series, and two y aspects', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'group', params: { field: 'extension' } }, @@ -180,53 +180,53 @@ describe('pointSeriesChartDataFromTable', function () { ] }); - let extensions = ['php', 'jpg', 'gif', 'css']; - let term = { + const extensions = ['php', 'jpg', 'gif', 'css']; + const term = { agg: vis.aggs[0], col: { title: 'extensions', aggConfig: vis.aggs[0] }, at: function (i) { return extensions[i % extensions.length]; } }; - let avg = { + const avg = { agg: vis.aggs[1], col: { title: 'average', aggConfig: vis.aggs[1] }, at: function (i) { return 75.444 * (i + 1); } }; - let date = { + const date = { agg: vis.aggs[2], col: { title: 'date', aggConfig: vis.aggs[2] }, at: function (i) { return moment().startOf('day').add(i, 'day').valueOf(); } }; - let max = { + const max = { agg: vis.aggs[3], col: { title: 'maximum', aggConfig: vis.aggs[3] }, at: function (i) { return 100 * (i + 1); } }; - let metricCount = 2; - let rowsPerSegment = 2; - let rowCount = extensions.length * rowsPerSegment; - let table = new Table(); + const metricCount = 2; + const rowsPerSegment = 2; + const rowCount = extensions.length * rowsPerSegment; + const table = new Table(); table.columns = [ date.col, term.col, avg.col, max.col ]; _.times(rowCount, function (i) { - let dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); - let termResult = new AggConfigResult(term.agg, dateResult, term.at(i)); - let avgResult = new AggConfigResult(avg.agg, termResult, avg.at(i)); - let maxResult = new AggConfigResult(max.agg, termResult, max.at(i)); + const dateResult = new AggConfigResult(date.agg, void 0, date.at(i)); + const termResult = new AggConfigResult(term.agg, dateResult, term.at(i)); + const avgResult = new AggConfigResult(avg.agg, termResult, avg.at(i)); + const maxResult = new AggConfigResult(max.agg, termResult, max.at(i)); table.rows.push([dateResult, termResult, avgResult, maxResult]); }); - let chartData = pointSeriesChartDataFromTable(vis, table); + const chartData = pointSeriesChartDataFromTable(vis, table); expect(chartData).to.be.an('object'); expect(chartData.series).to.be.an('array'); // one series for each extension, and then one for each metric inside expect(chartData.series).to.have.length(extensions.length * metricCount); chartData.series.forEach(function (siri, i) { // figure out the metric used to create this series - let metricAgg = siri.values[0].aggConfigResult.aggConfig; - let metric = avg.agg === metricAgg ? avg : max; + const metricAgg = siri.values[0].aggConfigResult.aggConfig; + const metric = avg.agg === metricAgg ? avg : max; expect(siri.values).to.have.length(rowsPerSegment); siri.values.forEach(function (point) { diff --git a/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js b/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js index db7763ca82772..1c3dc596f9fe5 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js +++ b/src/ui/public/agg_response/point_series/__tests__/_ordered_date_axis.js @@ -6,7 +6,7 @@ import ngMock from 'ng_mock'; import AggResponsePointSeriesOrderedDateAxisProvider from 'ui/agg_response/point_series/_ordered_date_axis'; describe('orderedDateAxis', function () { - let baseArgs = { + const baseArgs = { vis: { indexPattern: { timeFieldName: '@timestamp' @@ -37,7 +37,7 @@ describe('orderedDateAxis', function () { describe('xAxisFormatter', function () { it('sets the xAxisFormatter', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); expect(args.chart).to.have.property('xAxisFormatter'); @@ -45,10 +45,10 @@ describe('orderedDateAxis', function () { }); it('formats values using moment, and returns strings', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); - let val = '2014-08-06T12:34:01'; + const val = '2014-08-06T12:34:01'; expect(args.chart.xAxisFormatter(val)) .to.be(moment(val).format('hh:mm:ss')); }); @@ -56,7 +56,7 @@ describe('orderedDateAxis', function () { describe('ordered object', function () { it('sets date: true', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); expect(args.chart) @@ -67,21 +67,21 @@ describe('orderedDateAxis', function () { }); it('relies on agg.buckets for the interval', function () { - let args = _.cloneDeep(baseArgs); - let spy = sinon.spy(args.chart.aspects.x.agg.buckets, 'getInterval'); + const args = _.cloneDeep(baseArgs); + const spy = sinon.spy(args.chart.aspects.x.agg.buckets, 'getInterval'); orderedDateAxis(args.vis, args.chart); expect(spy).to.have.property('callCount', 1); }); it('sets the min/max when the buckets are bounded', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); orderedDateAxis(args.vis, args.chart); expect(moment.isMoment(args.chart.ordered.min)).to.be(true); expect(moment.isMoment(args.chart.ordered.max)).to.be(true); }); it('does not set the min/max when the buckets are unbounded', function () { - let args = _.cloneDeep(baseArgs); + const args = _.cloneDeep(baseArgs); args.chart.aspects.x.agg.buckets.getBounds = _.constant(); orderedDateAxis(args.vis, args.chart); expect(args.chart.ordered).to.not.have.property('min'); diff --git a/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js b/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js index 73c9e796f252b..5a54de473e578 100644 --- a/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js +++ b/src/ui/public/agg_response/point_series/__tests__/_tooltip_formatter.js @@ -23,7 +23,7 @@ describe('tooltipFormatter', function () { return $row.eq(i).text().trim(); } - let baseEvent = { + const baseEvent = { datum: { aggConfigResult: { aggConfig: agg('inner'), @@ -42,20 +42,20 @@ describe('tooltipFormatter', function () { }; it('returns html based on the mouse event', function () { - let event = _.cloneDeep(baseEvent); - let $el = $(tooltipFormatter(event)); - let $rows = $el.find('tr'); + const event = _.cloneDeep(baseEvent); + const $el = $(tooltipFormatter(event)); + const $rows = $el.find('tr'); expect($rows.size()).to.be(3); - let $row1 = $rows.eq(0).find('td'); + const $row1 = $rows.eq(0).find('td'); expect(cell($row1, 0)).to.be('inner'); expect(cell($row1, 1)).to.be('(3)'); - let $row2 = $rows.eq(1).find('td'); + const $row2 = $rows.eq(1).find('td'); expect(cell($row2, 0)).to.be('middle'); expect(cell($row2, 1)).to.be('(2)'); - let $row3 = $rows.eq(2).find('td'); + const $row3 = $rows.eq(2).find('td'); expect(cell($row3, 0)).to.be('top'); expect(cell($row3, 1)).to.be('(1)'); }); diff --git a/src/ui/public/agg_response/point_series/_fake_x_aspect.js b/src/ui/public/agg_response/point_series/_fake_x_aspect.js index 5f9516a421cc2..aa4f2b6ca56ae 100644 --- a/src/ui/public/agg_response/point_series/_fake_x_aspect.js +++ b/src/ui/public/agg_response/point_series/_fake_x_aspect.js @@ -2,10 +2,10 @@ import VisAggConfigProvider from 'ui/vis/agg_config'; import AggTypesAggTypeProvider from 'ui/agg_types/agg_type'; export default function PointSeriesFakeXAxis(Private) { - let AggConfig = Private(VisAggConfigProvider); - let AggType = Private(AggTypesAggTypeProvider); + const AggConfig = Private(VisAggConfigProvider); + const AggType = Private(AggTypesAggTypeProvider); - let allAgg = new AggType({ + const allAgg = new AggType({ name: 'all', title: 'All docs', ordered: false, @@ -13,7 +13,7 @@ export default function PointSeriesFakeXAxis(Private) { }); return function makeFakeXAxis(vis) { - let fake = new AggConfig(vis, { + const fake = new AggConfig(vis, { type: allAgg, schema: vis.type.schemas.all.byName.segment }); diff --git a/src/ui/public/agg_response/point_series/_get_aspects.js b/src/ui/public/agg_response/point_series/_get_aspects.js index f4978de298858..648a7f752b6ce 100644 --- a/src/ui/public/agg_response/point_series/_get_aspects.js +++ b/src/ui/public/agg_response/point_series/_get_aspects.js @@ -1,9 +1,9 @@ import _ from 'lodash'; import AggResponsePointSeriesFakeXAspectProvider from 'ui/agg_response/point_series/_fake_x_aspect'; export default function PointSeriesGetAspects(Private) { - let fakeXAspect = Private(AggResponsePointSeriesFakeXAspectProvider); + const fakeXAspect = Private(AggResponsePointSeriesFakeXAspectProvider); - let map = { + const map = { segment: 'x', metric: 'y', radius: 'z', @@ -12,12 +12,12 @@ export default function PointSeriesGetAspects(Private) { }; function columnToAspect(aspects, col, i) { - let schema = col.aggConfig.schema.name; + const schema = col.aggConfig.schema.name; - let name = map[schema]; + const name = map[schema]; if (!name) throw new TypeError('unknown schema name "' + schema + '"'); - let aspect = { + const aspect = { i: i, col: col, agg: col.aggConfig @@ -36,7 +36,7 @@ export default function PointSeriesGetAspects(Private) { * may be undefined, a single aspect, or an array of aspects. */ return function getAspects(vis, table) { - let aspects = _(table.columns) + const aspects = _(table.columns) // write each column into the aspects under it's group .transform(columnToAspect, {}) // unwrap groups that only have one value, and validate groups that have more diff --git a/src/ui/public/agg_response/point_series/_get_point.js b/src/ui/public/agg_response/point_series/_get_point.js index 5e72304a66f3c..2e79e9fbe831e 100644 --- a/src/ui/public/agg_response/point_series/_get_point.js +++ b/src/ui/public/agg_response/point_series/_get_point.js @@ -5,10 +5,10 @@ export default function PointSeriesGetPoint() { } return function getPoint(x, series, yScale, row, y, z) { - let zRow = z && row[z.i]; - let xRow = row[x.i]; + const zRow = z && row[z.i]; + const xRow = row[x.i]; - let point = { + const point = { x: unwrap(xRow, '_all'), xi: xRow && xRow.$order, y: unwrap(row[y.i]), diff --git a/src/ui/public/agg_response/point_series/_get_series.js b/src/ui/public/agg_response/point_series/_get_series.js index ed27cc386446b..23ce1683a09f0 100644 --- a/src/ui/public/agg_response/point_series/_get_series.js +++ b/src/ui/public/agg_response/point_series/_get_series.js @@ -2,25 +2,25 @@ import _ from 'lodash'; import AggResponsePointSeriesGetPointProvider from 'ui/agg_response/point_series/_get_point'; import AggResponsePointSeriesAddToSiriProvider from 'ui/agg_response/point_series/_add_to_siri'; export default function PointSeriesGetSeries(Private) { - let getPoint = Private(AggResponsePointSeriesGetPointProvider); - let addToSiri = Private(AggResponsePointSeriesAddToSiriProvider); + const getPoint = Private(AggResponsePointSeriesGetPointProvider); + const addToSiri = Private(AggResponsePointSeriesAddToSiriProvider); return function getSeries(rows, chart) { - let aspects = chart.aspects; - let multiY = _.isArray(aspects.y); - let yScale = chart.yScale; - let partGetPoint = _.partial(getPoint, aspects.x, aspects.series, yScale); + const aspects = chart.aspects; + const multiY = _.isArray(aspects.y); + const yScale = chart.yScale; + const partGetPoint = _.partial(getPoint, aspects.x, aspects.series, yScale); let series = _(rows) .transform(function (series, row) { if (!multiY) { - let point = partGetPoint(row, aspects.y, aspects.z); + const point = partGetPoint(row, aspects.y, aspects.z); if (point) addToSiri(series, point, point.series); return; } aspects.y.forEach(function (y) { - let point = partGetPoint(row, y, aspects.z); + const point = partGetPoint(row, y, aspects.z); if (!point) return; // use the point's y-axis as it's series by default, @@ -44,11 +44,11 @@ export default function PointSeriesGetSeries(Private) { if (multiY) { series = _.sortBy(series, function (siri) { - let firstVal = siri.values[0]; + const firstVal = siri.values[0]; let y; if (firstVal) { - let agg = firstVal.aggConfigResult.aggConfig; + const agg = firstVal.aggConfigResult.aggConfig; y = _.find(aspects.y, function (y) { return y.agg === agg; }); diff --git a/src/ui/public/agg_response/point_series/_init_x_axis.js b/src/ui/public/agg_response/point_series/_init_x_axis.js index 287bb3bdcaea4..abbd56e78bed4 100644 --- a/src/ui/public/agg_response/point_series/_init_x_axis.js +++ b/src/ui/public/agg_response/point_series/_init_x_axis.js @@ -1,13 +1,13 @@ export default function PointSeriesInitX() { return function initXAxis(chart) { - let x = chart.aspects.x; + const x = chart.aspects.x; chart.xAxisFormatter = x.agg ? x.agg.fieldFormatter() : String; chart.xAxisLabel = x.col.title; if (!x.agg || !x.agg.type.ordered) return; chart.ordered = {}; - let xAggOutput = x.agg.write(); + const xAggOutput = x.agg.write(); if (xAggOutput.params.interval) { chart.ordered.interval = xAggOutput.params.interval; } diff --git a/src/ui/public/agg_response/point_series/_init_y_axis.js b/src/ui/public/agg_response/point_series/_init_y_axis.js index edd3060fc85c2..2f2d2039deb19 100644 --- a/src/ui/public/agg_response/point_series/_init_y_axis.js +++ b/src/ui/public/agg_response/point_series/_init_y_axis.js @@ -2,8 +2,8 @@ import _ from 'lodash'; export default function PointSeriesInitYAxis() { return function initYAxis(chart) { - let y = chart.aspects.y; - let x = chart.aspects.x; + const y = chart.aspects.y; + const x = chart.aspects.x; if (_.isArray(y)) { // TODO: vis option should allow choosing this format @@ -14,7 +14,7 @@ export default function PointSeriesInitYAxis() { chart.yAxisLabel = y.col.title; } - let xAggOutput = x.agg.write(); + const xAggOutput = x.agg.write(); chart.yScale = xAggOutput.metricScale || null; }; }; diff --git a/src/ui/public/agg_response/point_series/_ordered_date_axis.js b/src/ui/public/agg_response/point_series/_ordered_date_axis.js index 08b1d962252f2..1a72b4d6e6e3a 100644 --- a/src/ui/public/agg_response/point_series/_ordered_date_axis.js +++ b/src/ui/public/agg_response/point_series/_ordered_date_axis.js @@ -2,9 +2,9 @@ import moment from 'moment'; export default function PointSeriesOrderedDateAxis(timefilter) { return function orderedDateAxis(vis, chart) { - let xAgg = chart.aspects.x.agg; - let buckets = xAgg.buckets; - let format = buckets.getScaledDateFormat(); + const xAgg = chart.aspects.x.agg; + const buckets = xAgg.buckets; + const format = buckets.getScaledDateFormat(); chart.xAxisFormatter = function (val) { return moment(val).format(format); @@ -15,8 +15,8 @@ export default function PointSeriesOrderedDateAxis(timefilter) { interval: buckets.getInterval(), }; - let axisOnTimeField = xAgg.fieldIsTimeField(); - let bounds = buckets.getBounds(); + const axisOnTimeField = xAgg.fieldIsTimeField(); + const bounds = buckets.getBounds(); if (bounds && axisOnTimeField) { chart.ordered.min = bounds.min; chart.ordered.max = bounds.max; diff --git a/src/ui/public/agg_response/point_series/_tooltip_formatter.js b/src/ui/public/agg_response/point_series/_tooltip_formatter.js index 715d692127d1e..c6e12fd7bf5b8 100644 --- a/src/ui/public/agg_response/point_series/_tooltip_formatter.js +++ b/src/ui/public/agg_response/point_series/_tooltip_formatter.js @@ -1,22 +1,22 @@ import $ from 'jquery'; export default function PointSeriesTooltipFormatter($compile, $rootScope) { - let $tooltipScope = $rootScope.$new(); - let $tooltip = $(require('ui/agg_response/point_series/_tooltip.html')); + const $tooltipScope = $rootScope.$new(); + const $tooltip = $(require('ui/agg_response/point_series/_tooltip.html')); $compile($tooltip)($tooltipScope); return function tooltipFormatter(event) { - let datum = event.datum; + const datum = event.datum; if (!datum || !datum.aggConfigResult) return ''; - let details = $tooltipScope.details = []; + const details = $tooltipScope.details = []; let result = { $parent: datum.aggConfigResult }; function addDetail(result) { - let agg = result.aggConfig; - let value = result.value; + const agg = result.aggConfig; + const value = result.value; - let detail = { + const detail = { value: agg.fieldFormatter()(value), label: agg.makeLabel() }; diff --git a/src/ui/public/agg_response/point_series/point_series.js b/src/ui/public/agg_response/point_series/point_series.js index 0a2ccd90729c4..eb057200db47d 100644 --- a/src/ui/public/agg_response/point_series/point_series.js +++ b/src/ui/public/agg_response/point_series/point_series.js @@ -7,23 +7,23 @@ import AggResponsePointSeriesOrderedDateAxisProvider from 'ui/agg_response/point import AggResponsePointSeriesTooltipFormatterProvider from 'ui/agg_response/point_series/_tooltip_formatter'; export default function PointSeriesProvider(Private) { - let getSeries = Private(AggResponsePointSeriesGetSeriesProvider); - let getAspects = Private(AggResponsePointSeriesGetAspectsProvider); - let initYAxis = Private(AggResponsePointSeriesInitYAxisProvider); - let initXAxis = Private(AggResponsePointSeriesInitXAxisProvider); - let setupOrderedDateXAxis = Private(AggResponsePointSeriesOrderedDateAxisProvider); - let tooltipFormatter = Private(AggResponsePointSeriesTooltipFormatterProvider); + const getSeries = Private(AggResponsePointSeriesGetSeriesProvider); + const getAspects = Private(AggResponsePointSeriesGetAspectsProvider); + const initYAxis = Private(AggResponsePointSeriesInitYAxisProvider); + const initXAxis = Private(AggResponsePointSeriesInitXAxisProvider); + const setupOrderedDateXAxis = Private(AggResponsePointSeriesOrderedDateAxisProvider); + const tooltipFormatter = Private(AggResponsePointSeriesTooltipFormatterProvider); return function pointSeriesChartDataFromTable(vis, table) { - let chart = {}; - let aspects = chart.aspects = getAspects(vis, table); + const chart = {}; + const aspects = chart.aspects = getAspects(vis, table); chart.tooltipFormatter = tooltipFormatter; initXAxis(chart); initYAxis(chart); - let datedX = aspects.x.agg.type.ordered && aspects.x.agg.type.ordered.date; + const datedX = aspects.x.agg.type.ordered && aspects.x.agg.type.ordered.date; if (datedX) { setupOrderedDateXAxis(vis, chart); } diff --git a/src/ui/public/agg_response/tabify/__tests__/_buckets.js b/src/ui/public/agg_response/tabify/__tests__/_buckets.js index e2ecc8e75d55d..ef34f4d3cafbd 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_buckets.js +++ b/src/ui/public/agg_response/tabify/__tests__/_buckets.js @@ -12,13 +12,13 @@ describe('Buckets wrapper', function () { function test(aggResp, count, keys) { it('reads the length', function () { - let buckets = new Buckets(aggResp); + const buckets = new Buckets(aggResp); expect(buckets).to.have.length(count); }); it('itterates properly, passing in the key', function () { - let buckets = new Buckets(aggResp); - let keysSent = []; + const buckets = new Buckets(aggResp); + const keysSent = []; buckets.forEach(function (bucket, key) { keysSent.push(key); }); @@ -29,7 +29,7 @@ describe('Buckets wrapper', function () { } describe('with object style buckets', function () { - let aggResp = { + const aggResp = { buckets: { '0-100': {}, '100-200': {}, @@ -37,14 +37,14 @@ describe('Buckets wrapper', function () { } }; - let count = 3; - let keys = ['0-100', '100-200', '200-300']; + const count = 3; + const keys = ['0-100', '100-200', '200-300']; test(aggResp, count, keys); }); describe('with array style buckets', function () { - let aggResp = { + const aggResp = { buckets: [ { key: '0-100', value: {} }, { key: '100-200', value: {} }, @@ -52,8 +52,8 @@ describe('Buckets wrapper', function () { ] }; - let count = 3; - let keys = ['0-100', '100-200', '200-300']; + const count = 3; + const keys = ['0-100', '100-200', '200-300']; test(aggResp, count, keys); }); diff --git a/src/ui/public/agg_response/tabify/__tests__/_get_columns.js b/src/ui/public/agg_response/tabify/__tests__/_get_columns.js index d8db8717c2dc0..e0b315d757bb3 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_get_columns.js +++ b/src/ui/public/agg_response/tabify/__tests__/_get_columns.js @@ -16,11 +16,11 @@ describe('get columns', function () { })); it('should inject a count metric if no aggs exist', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie' }); while (vis.aggs.length) vis.aggs.pop(); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(1); expect(columns[0]).to.have.property('aggConfig'); @@ -28,14 +28,14 @@ describe('get columns', function () { }); it('should inject a count metric if only buckets exist', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } } ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(2); expect(columns[1]).to.have.property('aggConfig'); @@ -43,7 +43,7 @@ describe('get columns', function () { }); it('should inject the metric after each bucket if the vis is hierarchical', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, @@ -53,7 +53,7 @@ describe('get columns', function () { ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(8); columns.forEach(function (column, i) { @@ -63,7 +63,7 @@ describe('get columns', function () { }); it('should inject the multiple metrics after each bucket if the vis is hierarchical', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, @@ -75,7 +75,7 @@ describe('get columns', function () { ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); function checkColumns(column, i) { expect(column).to.have.property('aggConfig'); @@ -94,13 +94,13 @@ describe('get columns', function () { expect(columns).to.have.length(12); for (let i = 0; i < columns.length; i += 3) { - let counts = { buckets: 0, metrics: 0 }; + const counts = { buckets: 0, metrics: 0 }; columns.slice(i, i + 3).forEach(checkColumns); } }); it('should put all metrics at the end of the columns if the vis is not hierarchical', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, @@ -112,7 +112,7 @@ describe('get columns', function () { ] }); - let columns = getColumns(vis); + const columns = getColumns(vis); expect(columns).to.have.length(6); // sum should be last diff --git a/src/ui/public/agg_response/tabify/__tests__/_integration.js b/src/ui/public/agg_response/tabify/__tests__/_integration.js index ea5d6096219d6..528a732f29d09 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_integration.js +++ b/src/ui/public/agg_response/tabify/__tests__/_integration.js @@ -26,13 +26,13 @@ describe('tabifyAggResponse Integration', function () { } it('transforms a simple response properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); normalizeIds(vis); - let resp = tabifyAggResponse(vis, fixtures.metricOnly, { canSplit: false }); + const resp = tabifyAggResponse(vis, fixtures.metricOnly, { canSplit: false }); expect(resp).to.not.have.property('tables'); expect(resp).to.have.property('rows').and.property('columns'); @@ -81,7 +81,7 @@ describe('tabifyAggResponse Integration', function () { function expectRootGroup(rootTableGroup, expectInnerTables) { expect(rootTableGroup).to.have.property('tables'); - let tables = rootTableGroup.tables; + const tables = rootTableGroup.tables; expect(tables).to.be.an('array').and.have.length(3); expectExtensionSplit(tables[0], 'png', expectInnerTables); expectExtensionSplit(tables[1], 'css', expectInnerTables); @@ -155,7 +155,7 @@ describe('tabifyAggResponse Integration', function () { // only complete rows, and only put the metrics at the end. vis.isHierarchical = _.constant(false); - let tabbed = tabifyAggResponse(vis, esResp); + const tabbed = tabifyAggResponse(vis, esResp); expectRootGroup(tabbed, function expectTable(table, splitKey) { expectColumns(table, [src, os, avg]); @@ -181,7 +181,7 @@ describe('tabifyAggResponse Integration', function () { // the existing bucket and it's metric vis.isHierarchical = _.constant(true); - let tabbed = tabifyAggResponse(vis, esResp, { + const tabbed = tabifyAggResponse(vis, esResp, { partialRows: true }); @@ -215,7 +215,7 @@ describe('tabifyAggResponse Integration', function () { // the end vis.isHierarchical = _.constant(true); - let tabbed = tabifyAggResponse(vis, esResp, { + const tabbed = tabifyAggResponse(vis, esResp, { partialRows: true, minimalColumns: true }); @@ -247,7 +247,7 @@ describe('tabifyAggResponse Integration', function () { // create metric columns after each bucket vis.isHierarchical = _.constant(false); - let tabbed = tabifyAggResponse(vis, esResp, { + const tabbed = tabifyAggResponse(vis, esResp, { minimalColumns: false }); diff --git a/src/ui/public/agg_response/tabify/__tests__/_response_writer.js b/src/ui/public/agg_response/tabify/__tests__/_response_writer.js index e2f601a30253e..7329345442215 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_response_writer.js +++ b/src/ui/public/agg_response/tabify/__tests__/_response_writer.js @@ -42,15 +42,15 @@ describe('ResponseWriter class', function () { defineSetup(true); it('gets the columns for the vis', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(getColumns).to.have.property('callCount', 1); expect(getColumns.firstCall.args[0]).to.be(vis); }); it('collects the aggConfigs from each column in aggStack', function () { - let aggs = [ + const aggs = [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp' } }, { type: 'terms', schema: 'segment', params: { field: 'extension' } }, { type: 'avg', schema: 'metric', params: { field: 'bytes' } } @@ -60,12 +60,12 @@ describe('ResponseWriter class', function () { return { aggConfig: agg }; })); - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: aggs }); - let writer = new ResponseWriter(vis); + const writer = new ResponseWriter(vis); expect(writer.aggStack).to.be.an('array'); expect(writer.aggStack).to.have.length(aggs.length); writer.aggStack.forEach(function (agg, i) { @@ -74,40 +74,40 @@ describe('ResponseWriter class', function () { }); it('sets canSplit=true by default', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(writer).to.have.property('canSplit', true); }); it('sets canSplit=false when config says to', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis, { canSplit: false }); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis, { canSplit: false }); expect(writer).to.have.property('canSplit', false); }); describe('sets partialRows', function () { it('to the value of the config if set', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let partial = Boolean(Math.round(Math.random())); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const partial = Boolean(Math.round(Math.random())); - let writer = new ResponseWriter(vis, { partialRows: partial }); + const writer = new ResponseWriter(vis, { partialRows: partial }); expect(writer).to.have.property('partialRows', partial); }); it('to the value of vis.isHierarchical if no config', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let hierarchical = Boolean(Math.round(Math.random())); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const hierarchical = Boolean(Math.round(Math.random())); sinon.stub(vis, 'isHierarchical').returns(hierarchical); - let writer = new ResponseWriter(vis, {}); + const writer = new ResponseWriter(vis, {}); expect(writer).to.have.property('partialRows', hierarchical); }); }); it('starts off with a root TableGroup', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const writer = new ResponseWriter(vis); expect(writer.root).to.be.a(TableGroup); expect(writer.splitStack).to.be.an('array'); expect(writer.splitStack).to.have.length(1); @@ -120,29 +120,29 @@ describe('ResponseWriter class', function () { describe('#response()', function () { it('returns the root TableGroup if splitting', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(writer.response()).to.be(writer.root); }); it('returns the first table if not splitting', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis, { canSplit: false }); - let table = writer._table(); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis, { canSplit: false }); + const table = writer._table(); expect(writer.response()).to.be(table); }); it('adds columns to all of the tables', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', params: { field: '_type' }, schema: 'split' }, { type: 'count', schema: 'metric' } ] }); - let buckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); - let writer = new ResponseWriter(vis); - let tables = []; + const buckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); + const writer = new ResponseWriter(vis); + const tables = []; writer.split(vis.aggs[0], buckets, function () { writer.cell(vis.aggs[1], 100, function () { @@ -154,11 +154,11 @@ describe('ResponseWriter class', function () { expect(table.columns == null).to.be(true); }); - let resp = writer.response(); + const resp = writer.response(); expect(resp).to.be.a(TableGroup); expect(resp.tables).to.have.length(2); - let nginx = resp.tables.shift(); + const nginx = resp.tables.shift(); expect(nginx).to.have.property('aggConfig', vis.aggs[0]); expect(nginx).to.have.property('key', 'nginx'); expect(nginx.tables).to.have.length(1); @@ -166,7 +166,7 @@ describe('ResponseWriter class', function () { expect(_.contains(tables, table)).to.be(true); }); - let apache = resp.tables.shift(); + const apache = resp.tables.shift(); expect(apache).to.have.property('aggConfig', vis.aggs[0]); expect(apache).to.have.property('key', 'apache'); expect(apache.tables).to.have.length(1); @@ -184,16 +184,16 @@ describe('ResponseWriter class', function () { describe('#split()', function () { it('with break if the user has specified that splitting is to be disabled', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'split', params: { field: '_type' } }, { type: 'count', schema: 'metric' } ] }); - let agg = vis.aggs.bySchemaName.split[0]; - let buckets = new Buckets({ buckets: [ { key: 'apache' } ]}); - let writer = new ResponseWriter(vis, { canSplit: false }); + const agg = vis.aggs.bySchemaName.split[0]; + const buckets = new Buckets({ buckets: [ { key: 'apache' } ]}); + const writer = new ResponseWriter(vis, { canSplit: false }); expect(function () { writer.split(agg, buckets, _.noop); @@ -201,7 +201,7 @@ describe('ResponseWriter class', function () { }); it('forks the acrStack and rewrites the parents', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', params: { field: 'extension' }, schema: 'segment' }, @@ -211,10 +211,10 @@ describe('ResponseWriter class', function () { ] }); - let writer = new ResponseWriter(vis, { asAggConfigResults: true }); - let extensions = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); - let types = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); - let os = new Buckets({ buckets: [ { key: 'window' }, { key: 'osx' } ] }); + const writer = new ResponseWriter(vis, { asAggConfigResults: true }); + const extensions = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); + const types = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); + const os = new Buckets({ buckets: [ { key: 'window' }, { key: 'osx' } ] }); extensions.forEach(function (b, extension) { writer.cell(vis.aggs[0], extension, function () { @@ -230,11 +230,11 @@ describe('ResponseWriter class', function () { }); }); - let tables = _.flattenDeep(_.pluck(writer.response().tables, 'tables')); + const tables = _.flattenDeep(_.pluck(writer.response().tables, 'tables')); expect(tables.length).to.be(types.length); // collect the far left acr from each table - let leftAcrs = _.pluck(tables, 'rows[0][0]'); + const leftAcrs = _.pluck(tables, 'rows[0][0]'); leftAcrs.forEach(function (acr, i, acrs) { expect(acr.aggConfig).to.be(vis.aggs[0]); @@ -243,7 +243,7 @@ describe('ResponseWriter class', function () { // for all but the last acr, compare to the next if (i + 1 >= acrs.length) return; - let acr2 = leftAcrs[i + 1]; + const acr2 = leftAcrs[i + 1]; expect(acr.key).to.be(acr2.key); expect(acr.value).to.be(acr2.value); @@ -258,8 +258,8 @@ describe('ResponseWriter class', function () { describe('#cell()', function () { it('logs a cell in the ResponseWriters row buffer, calls the block arg, then removes the value from the buffer', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); expect(writer.rowBuffer).to.have.length(0); writer.cell({}, 500, function () { @@ -272,10 +272,10 @@ describe('ResponseWriter class', function () { describe('#row()', function () { it('writes the ResponseWriters internal rowBuffer into a table', function () { - let vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let writer = new ResponseWriter(vis); + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); + const writer = new ResponseWriter(vis); - let table = writer._table(); + const table = writer._table(); writer.cell({}, 1, function () { writer.cell({}, 2, function () { writer.cell({}, 3, function () { @@ -289,7 +289,7 @@ describe('ResponseWriter class', function () { }); it('always writes to the table group at the top of the split stack', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'split', params: { field: '_type' } }, @@ -298,20 +298,20 @@ describe('ResponseWriter class', function () { { type: 'count', schema: 'metric' } ] }); - let splits = vis.aggs.bySchemaName.split; + const splits = vis.aggs.bySchemaName.split; - let type = splits[0]; - let typeBuckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); + const type = splits[0]; + const typeBuckets = new Buckets({ buckets: [ { key: 'nginx' }, { key: 'apache' } ] }); - let ext = splits[1]; - let extBuckets = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); + const ext = splits[1]; + const extBuckets = new Buckets({ buckets: [ { key: 'jpg' }, { key: 'png' } ] }); - let os = splits[2]; - let osBuckets = new Buckets({ buckets: [ { key: 'windows' }, { key: 'mac' } ] }); + const os = splits[2]; + const osBuckets = new Buckets({ buckets: [ { key: 'windows' }, { key: 'mac' } ] }); - let count = vis.aggs[3]; + const count = vis.aggs[3]; - let writer = new ResponseWriter(vis); + const writer = new ResponseWriter(vis); writer.split(type, typeBuckets, function () { writer.split(ext, extBuckets, function () { writer.split(os, osBuckets, function (bucket, key) { @@ -322,7 +322,7 @@ describe('ResponseWriter class', function () { }); }); - let resp = writer.response(); + const resp = writer.response(); let sum = 0; let tables = 0; (function recurse(t) { @@ -347,7 +347,7 @@ describe('ResponseWriter class', function () { }); it('writes partial rows for hierarchical vis', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'terms', schema: 'segment', params: { field: '_type' }}, @@ -355,8 +355,8 @@ describe('ResponseWriter class', function () { ] }); - let writer = new ResponseWriter(vis); - let table = writer._table(); + const writer = new ResponseWriter(vis); + const table = writer._table(); writer.cell(vis.aggs[0], 'apache', function () { writer.row(); }); @@ -366,7 +366,7 @@ describe('ResponseWriter class', function () { }); it('skips partial rows for non-hierarchical vis', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'segment', params: { field: '_type' }}, @@ -374,8 +374,8 @@ describe('ResponseWriter class', function () { ] }); - let writer = new ResponseWriter(vis); - let table = writer._table(); + const writer = new ResponseWriter(vis); + const table = writer._table(); writer.cell(vis.aggs[0], 'apache', function () { writer.row(); }); diff --git a/src/ui/public/agg_response/tabify/__tests__/_table.js b/src/ui/public/agg_response/tabify/__tests__/_table.js index 4a9011548bc64..71c96c90756c4 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_table.js +++ b/src/ui/public/agg_response/tabify/__tests__/_table.js @@ -12,16 +12,16 @@ describe('Table class', function () { })); it('exposes rows array, but not the columns', function () { - let table = new Table(); + const table = new Table(); expect(table.rows).to.be.an('array'); expect(table.columns == null).to.be.ok(); }); describe('#aggConfig', function () { it('accepts a column from the table and returns its agg config', function () { - let table = new Table(); - let football = {}; - let column = { + const table = new Table(); + const football = {}; + const column = { aggConfig: football }; @@ -30,7 +30,7 @@ describe('Table class', function () { it('throws a TypeError if the column is malformed', function () { expect(function () { - let notAColumn = {}; + const notAColumn = {}; (new Table()).aggConfig(notAColumn); }).to.throwException(TypeError); }); @@ -38,12 +38,12 @@ describe('Table class', function () { describe('#title', function () { it('returns nothing if the table is not part of a table group', function () { - let table = new Table(); + const table = new Table(); expect(table.title()).to.be(''); }); it('returns the title of the TableGroup if the table is part of one', function () { - let table = new Table(); + const table = new Table(); table.$parent = { title: 'TableGroup Title', tables: [table] @@ -55,9 +55,9 @@ describe('Table class', function () { describe('#field', function () { it('calls the columns aggConfig#getField() method', function () { - let table = new Table(); - let football = {}; - let column = { + const table = new Table(); + const football = {}; + const column = { aggConfig: { getField: _.constant(football) } @@ -69,9 +69,9 @@ describe('Table class', function () { describe('#fieldFormatter', function () { it('calls the columns aggConfig#fieldFormatter() method', function () { - let table = new Table(); - let football = {}; - let column = { + const table = new Table(); + const football = {}; + const column = { aggConfig: { fieldFormatter: _.constant(football) } diff --git a/src/ui/public/agg_response/tabify/__tests__/_table_group.js b/src/ui/public/agg_response/tabify/__tests__/_table_group.js index 5455caa143f34..d880596d45852 100644 --- a/src/ui/public/agg_response/tabify/__tests__/_table_group.js +++ b/src/ui/public/agg_response/tabify/__tests__/_table_group.js @@ -10,7 +10,7 @@ describe('Table Group class', function () { })); it('exposes tables array and empty aggConfig, key and title', function () { - let tableGroup = new TableGroup(); + const tableGroup = new TableGroup(); expect(tableGroup.tables).to.be.an('array'); expect(tableGroup.aggConfig).to.be(null); expect(tableGroup.key).to.be(null); diff --git a/src/ui/public/agg_response/tabify/_buckets.js b/src/ui/public/agg_response/tabify/_buckets.js index 7d05c83a882b1..001147c460675 100644 --- a/src/ui/public/agg_response/tabify/_buckets.js +++ b/src/ui/public/agg_response/tabify/_buckets.js @@ -15,7 +15,7 @@ export default function AggResponseBucketsProvider() { } Buckets.prototype.forEach = function (fn) { - let buckets = this.buckets; + const buckets = this.buckets; if (this.objectMode) { this._keys.forEach(function (key) { diff --git a/src/ui/public/agg_response/tabify/_get_columns.js b/src/ui/public/agg_response/tabify/_get_columns.js index b9268891cadc3..a4f2e9041ebd9 100644 --- a/src/ui/public/agg_response/tabify/_get_columns.js +++ b/src/ui/public/agg_response/tabify/_get_columns.js @@ -1,10 +1,10 @@ import _ from 'lodash'; import VisAggConfigProvider from 'ui/vis/agg_config'; export default function GetColumnsProvider(Private) { - let AggConfig = Private(VisAggConfigProvider); + const AggConfig = Private(VisAggConfigProvider); return function getColumns(vis, minimal) { - let aggs = vis.aggs.getResponseAggs(); + const aggs = vis.aggs.getResponseAggs(); if (minimal == null) minimal = !vis.isHierarchical(); @@ -23,10 +23,10 @@ export default function GetColumnsProvider(Private) { } // supposed to be bucket,...metrics,bucket,...metrics - let columns = []; + const columns = []; // seperate the metrics - let grouped = _.groupBy(aggs, function (agg) { + const grouped = _.groupBy(aggs, function (agg) { return agg.schema.group; }); diff --git a/src/ui/public/agg_response/tabify/_response_writer.js b/src/ui/public/agg_response/tabify/_response_writer.js index 53f1ee01782ac..d023392815a7f 100644 --- a/src/ui/public/agg_response/tabify/_response_writer.js +++ b/src/ui/public/agg_response/tabify/_response_writer.js @@ -4,9 +4,9 @@ import AggResponseTabifyTableProvider from 'ui/agg_response/tabify/_table'; import AggResponseTabifyTableGroupProvider from 'ui/agg_response/tabify/_table_group'; import AggResponseTabifyGetColumnsProvider from 'ui/agg_response/tabify/_get_columns'; export default function TabbedAggResponseWriterProvider(Private) { - let Table = Private(AggResponseTabifyTableProvider); - let TableGroup = Private(AggResponseTabifyTableGroupProvider); - let getColumns = Private(AggResponseTabifyGetColumnsProvider); + const Table = Private(AggResponseTabifyTableProvider); + const TableGroup = Private(AggResponseTabifyTableGroupProvider); + const getColumns = Private(AggResponseTabifyGetColumnsProvider); _.class(SplitAcr).inherits(AggConfigResult); @@ -25,7 +25,7 @@ export default function TabbedAggResponseWriterProvider(Private) { this.opts = opts || {}; this.rowBuffer = []; - let visIsHier = vis.isHierarchical(); + const visIsHier = vis.isHierarchical(); // do the options allow for splitting? we will only split if true and // tabify calls the split method. @@ -67,9 +67,9 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {Table/TableGroup} table - the created table */ TabbedAggResponseWriter.prototype._table = function (group, agg, key) { - let Class = (group) ? TableGroup : Table; - let table = new Class(); - let parent = this.splitStack[0]; + const Class = (group) ? TableGroup : Table; + const table = new Class(); + const parent = this.splitStack[0]; if (group) { table.aggConfig = agg; @@ -95,7 +95,7 @@ export default function TabbedAggResponseWriterProvider(Private) { * @param {function} block - a function to execute for each sub bucket */ TabbedAggResponseWriter.prototype.split = function (agg, buckets, block) { - let self = this; + const self = this; if (!self.canSplit) { throw new Error('attempted to split when splitting is disabled'); @@ -127,7 +127,7 @@ export default function TabbedAggResponseWriterProvider(Private) { }; TabbedAggResponseWriter.prototype._removeAggFromColumns = function (agg) { - let i = _.findIndex(this.columns, function (col) { + const i = _.findIndex(this.columns, function (col) { return col.aggConfig === agg; }); @@ -140,8 +140,8 @@ export default function TabbedAggResponseWriterProvider(Private) { // hierarchical vis creats additional columns for each bucket // we will remove those too - let mCol = this.columns.splice(i, 1).pop(); - let mI = _.findIndex(this.aggStack, function (agg) { + const mCol = this.columns.splice(i, 1).pop(); + const mI = _.findIndex(this.aggStack, function (agg) { return agg === mCol.aggConfig; }); @@ -160,8 +160,8 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {SplitAcr} - the AggConfigResult created for the split bucket */ TabbedAggResponseWriter.prototype._injectParentSplit = function (agg, key) { - let oldList = this.acrStack; - let newList = this.acrStack = []; + const oldList = this.acrStack; + const newList = this.acrStack = []; // walk from right to left through the old stack // and move things to the new stack @@ -175,7 +175,7 @@ export default function TabbedAggResponseWriterProvider(Private) { // walk from right to left, emptying the previous list while (oldList.length) { - let acr = oldList.pop(); + const acr = oldList.pop(); // ignore other splits if (acr instanceof SplitAcr) { @@ -189,11 +189,11 @@ export default function TabbedAggResponseWriterProvider(Private) { newList.unshift(injected); } - let newAcr = new AggConfigResult(acr.aggConfig, newList[0], acr.value, acr.aggConfig.getKey(acr)); + const newAcr = new AggConfigResult(acr.aggConfig, newList[0], acr.value, acr.aggConfig.getKey(acr)); newList.unshift(newAcr); // and replace the acr in the row buffer if its there - let rowI = this.rowBuffer.indexOf(acr); + const rowI = this.rowBuffer.indexOf(acr); if (rowI > -1) { this.rowBuffer[rowI] = newAcr; } @@ -215,7 +215,7 @@ export default function TabbedAggResponseWriterProvider(Private) { value = new AggConfigResult(agg, this.acrStack[0], value, value); } - let staskResult = this.asAggConfigResults && value.type === 'bucket'; + const staskResult = this.asAggConfigResults && value.type === 'bucket'; this.rowBuffer.push(value); if (staskResult) this.acrStack.unshift(value); @@ -237,14 +237,14 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {undefined} */ TabbedAggResponseWriter.prototype.row = function (buffer) { - let cells = buffer || this.rowBuffer.slice(0); + const cells = buffer || this.rowBuffer.slice(0); if (!this.partialRows && cells.length < this.columns.length) { return; } - let split = this.splitStack[0]; - let table = split.tables[0] || this._table(false); + const split = this.splitStack[0]; + const table = split.tables[0] || this._table(false); while (cells.length < this.columns.length) cells.push(''); table.rows.push(cells); @@ -257,7 +257,7 @@ export default function TabbedAggResponseWriterProvider(Private) { * @return {object} - the final table-tree */ TabbedAggResponseWriter.prototype.response = function () { - let columns = this.columns; + const columns = this.columns; // give the columns some metadata columns.map(function (col) { @@ -272,7 +272,7 @@ export default function TabbedAggResponseWriterProvider(Private) { if (this.canSplit) return this.root; - let table = this.root.tables[0]; + const table = this.root.tables[0]; if (!table) return; delete table.$parent; diff --git a/src/ui/public/agg_response/tabify/tabify.js b/src/ui/public/agg_response/tabify/tabify.js index 722a1a12b8032..36296bf2f7377 100644 --- a/src/ui/public/agg_response/tabify/tabify.js +++ b/src/ui/public/agg_response/tabify/tabify.js @@ -4,15 +4,15 @@ import AggResponseTabifyResponseWriterProvider from 'ui/agg_response/tabify/_res import AggResponseTabifyBucketsProvider from 'ui/agg_response/tabify/_buckets'; export default function tabifyAggResponseProvider(Private, Notifier) { - let AggConfig = Private(VisAggConfigProvider); - let TabbedAggResponseWriter = Private(AggResponseTabifyResponseWriterProvider); - let Buckets = Private(AggResponseTabifyBucketsProvider); - let notify = new Notifier({ location: 'agg_response/tabify'}); + const AggConfig = Private(VisAggConfigProvider); + const TabbedAggResponseWriter = Private(AggResponseTabifyResponseWriterProvider); + const Buckets = Private(AggResponseTabifyBucketsProvider); + const notify = new Notifier({ location: 'agg_response/tabify'}); function tabifyAggResponse(vis, esResponse, respOpts) { - let write = new TabbedAggResponseWriter(vis, respOpts); + const write = new TabbedAggResponseWriter(vis, respOpts); - let topLevelBucket = _.assign({}, esResponse.aggregations, { + const topLevelBucket = _.assign({}, esResponse.aggregations, { doc_count: esResponse.hits.total }); @@ -31,13 +31,13 @@ export default function tabifyAggResponseProvider(Private, Notifier) { * @returns {undefined} */ function collectBucket(write, bucket, key) { - let agg = write.aggStack.shift(); + const agg = write.aggStack.shift(); switch (agg.schema.group) { case 'buckets': - let buckets = new Buckets(bucket[agg.id]); + const buckets = new Buckets(bucket[agg.id]); if (buckets.length) { - let splitting = write.canSplit && agg.schema.name === 'split'; + const splitting = write.canSplit && agg.schema.name === 'split'; if (splitting) { write.split(agg, buckets, function forEachBucket(subBucket, key) { collectBucket(write, subBucket, agg.getKey(subBucket), key); @@ -63,7 +63,7 @@ export default function tabifyAggResponseProvider(Private, Notifier) { } break; case 'metrics': - let value = agg.getValue(bucket); + const value = agg.getValue(bucket); write.cell(agg, value, function () { if (!write.aggStack.length) { // row complete @@ -82,7 +82,7 @@ export default function tabifyAggResponseProvider(Private, Notifier) { // write empty values for each bucket agg, then write // the metrics from the initial bucket using collectBucket() function passEmptyBuckets(write, bucket, key) { - let agg = write.aggStack.shift(); + const agg = write.aggStack.shift(); switch (agg.schema.group) { case 'metrics': diff --git a/src/ui/public/agg_table/__tests__/_group.js b/src/ui/public/agg_table/__tests__/_group.js index 88c7cb92092ed..31bdc70eb5aa5 100644 --- a/src/ui/public/agg_table/__tests__/_group.js +++ b/src/ui/public/agg_table/__tests__/_group.js @@ -34,13 +34,13 @@ describe('AggTableGroup Directive', function () { it('renders a simple split response properly', function () { - let vis = new Vis(indexPattern, 'table'); + const vis = new Vis(indexPattern, 'table'); $scope.group = tabifyAggResponse(vis, fixtures.metricOnly); $scope.sort = { columnIndex: null, direction: null }; - let $el = $(''); + const $el = $(''); $compile($el)($scope); $scope.$digest(); @@ -50,7 +50,7 @@ describe('AggTableGroup Directive', function () { }); it('renders nothing if the table list is empty', function () { - let $el = $(''); + const $el = $(''); $scope.group = { tables: [] @@ -59,12 +59,12 @@ describe('AggTableGroup Directive', function () { $compile($el)($scope); $scope.$digest(); - let $subTables = $el.find('kbn-agg-table'); + const $subTables = $el.find('kbn-agg-table'); expect($subTables.size()).to.be(0); }); it('renders a complex response properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -77,15 +77,15 @@ describe('AggTableGroup Directive', function () { agg.id = 'agg_' + (i + 1); }); - let group = $scope.group = tabifyAggResponse(vis, fixtures.threeTermBuckets); - let $el = $(''); + const group = $scope.group = tabifyAggResponse(vis, fixtures.threeTermBuckets); + const $el = $(''); $compile($el)($scope); $scope.$digest(); - let $subTables = $el.find('kbn-agg-table'); + const $subTables = $el.find('kbn-agg-table'); expect($subTables.size()).to.be(3); - let $subTableHeaders = $el.find('.agg-table-group-header'); + const $subTableHeaders = $el.find('.agg-table-group-header'); expect($subTableHeaders.size()).to.be(3); $subTableHeaders.each(function (i) { diff --git a/src/ui/public/agg_table/__tests__/_table.js b/src/ui/public/agg_table/__tests__/_table.js index 3de485472d6b7..37565b0ca503b 100644 --- a/src/ui/public/agg_table/__tests__/_table.js +++ b/src/ui/public/agg_table/__tests__/_table.js @@ -35,10 +35,10 @@ describe('AggTable Directive', function () { it('renders a simple response properly', function () { - let vis = new Vis(indexPattern, 'table'); + const vis = new Vis(indexPattern, 'table'); $scope.table = tabifyAggResponse(vis, fixtures.metricOnly, { canSplit: false }); - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); expect($el.find('tbody').size()).to.be(1); @@ -48,14 +48,14 @@ describe('AggTable Directive', function () { it('renders nothing if the table is empty', function () { $scope.table = null; - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); expect($el.find('tbody').size()).to.be(0); }); it('renders a complex response properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, @@ -69,27 +69,27 @@ describe('AggTable Directive', function () { }); $scope.table = tabifyAggResponse(vis, fixtures.threeTermBuckets, { canSplit: false }); - let $el = $(''); + const $el = $(''); $compile($el)($scope); $scope.$digest(); expect($el.find('tbody').size()).to.be(1); - let $rows = $el.find('tbody tr'); + const $rows = $el.find('tbody tr'); expect($rows.size()).to.be.greaterThan(0); function validBytes(str) { expect(str).to.match(/^\d+$/); - let bytesAsNum = _.parseInt(str); + const bytesAsNum = _.parseInt(str); expect(bytesAsNum === 0 || bytesAsNum > 1000).to.be.ok(); } $rows.each(function (i) { // 6 cells in every row - let $cells = $(this).find('td'); + const $cells = $(this).find('td'); expect($cells.size()).to.be(6); - let txts = $cells.map(function () { + const txts = $cells.map(function () { return $(this).text().trim(); }); @@ -109,11 +109,11 @@ describe('AggTable Directive', function () { describe('aggTable.toCsv()', function () { it('escapes and formats the rows and columns properly', function () { - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); - let $tableScope = $el.isolateScope(); - let aggTable = $tableScope.aggTable; + const $tableScope = $el.isolateScope(); + const aggTable = $tableScope.aggTable; $tableScope.table = { columns: [ @@ -150,13 +150,13 @@ describe('AggTable Directive', function () { }); it('calls _saveAs properly', function () { - let $el = $compile('')($scope); + const $el = $compile('')($scope); $scope.$digest(); - let $tableScope = $el.isolateScope(); - let aggTable = $tableScope.aggTable; + const $tableScope = $el.isolateScope(); + const aggTable = $tableScope.aggTable; - let saveAs = sinon.stub(aggTable, '_saveAs'); + const saveAs = sinon.stub(aggTable, '_saveAs'); $tableScope.table = { columns: [ { title: 'one' }, @@ -172,7 +172,7 @@ describe('AggTable Directive', function () { aggTable.exportAsCsv(); expect(saveAs.callCount).to.be(1); - let call = saveAs.getCall(0); + const call = saveAs.getCall(0); expect(call.args[0]).to.be.a(FakeBlob); expect(call.args[0].slices).to.eql([ 'one,two,"with double-quotes("")"' + '\r\n' + @@ -185,12 +185,12 @@ describe('AggTable Directive', function () { }); it('should use the export-title attribute', function () { - let expected = 'export file name'; - let $el = $compile(``)($scope); + const expected = 'export file name'; + const $el = $compile(``)($scope); $scope.$digest(); - let $tableScope = $el.isolateScope(); - let aggTable = $tableScope.aggTable; + const $tableScope = $el.isolateScope(); + const aggTable = $tableScope.aggTable; $tableScope.table = { columns: [], rows: [] diff --git a/src/ui/public/agg_table/agg_table.js b/src/ui/public/agg_table/agg_table.js index d7bd8b7565a54..f1c9b20be4201 100644 --- a/src/ui/public/agg_table/agg_table.js +++ b/src/ui/public/agg_table/agg_table.js @@ -27,7 +27,7 @@ uiModules return compileRecursiveDirective.compile($el); }, controller: function ($scope) { - let self = this; + const self = this; self._saveAs = require('@spalger/filesaver').saveAs; self.csv = { @@ -36,15 +36,15 @@ uiModules }; self.exportAsCsv = function (formatted) { - let csv = new Blob([self.toCsv(formatted)], { type: 'text/plain;charset=utf-8' }); + const csv = new Blob([self.toCsv(formatted)], { type: 'text/plain;charset=utf-8' }); self._saveAs(csv, self.csv.filename); }; self.toCsv = function (formatted) { - let rows = $scope.table.rows; - let columns = formatted ? $scope.formattedColumns : $scope.table.columns; - let nonAlphaNumRE = /[^a-zA-Z0-9]/; - let allDoubleQuoteRE = /"/g; + const rows = $scope.table.rows; + const columns = formatted ? $scope.formattedColumns : $scope.table.columns; + const nonAlphaNumRE = /[^a-zA-Z0-9]/; + const allDoubleQuoteRE = /"/g; function escape(val) { if (!formatted && _.isObject(val)) val = val.valueOf(); @@ -56,7 +56,7 @@ uiModules } // escape each cell in each row - let csvRows = rows.map(function (row) { + const csvRows = rows.map(function (row) { return row.map(escape); }); @@ -71,7 +71,7 @@ uiModules }; $scope.$watch('table', function () { - let table = $scope.table; + const table = $scope.table; if (!table) { $scope.rows = null; @@ -82,14 +82,14 @@ uiModules self.csv.filename = ($scope.exportTitle || table.title() || 'table') + '.csv'; $scope.rows = table.rows; $scope.formattedColumns = table.columns.map(function (col, i) { - let agg = $scope.table.aggConfig(col); - let field = agg.getField(); - let formattedColumn = { + const agg = $scope.table.aggConfig(col); + const field = agg.getField(); + const formattedColumn = { title: col.title, filterable: field && field.filterable && agg.schema.group === 'buckets' }; - let last = i === (table.columns.length - 1); + const last = i === (table.columns.length - 1); if (last || (agg.schema.group === 'metrics')) { formattedColumn.class = 'visualize-table-right'; diff --git a/src/ui/public/agg_table/agg_table_group.js b/src/ui/public/agg_table/agg_table_group.js index 2cd1031182ba4..cff0e1180f951 100644 --- a/src/ui/public/agg_table/agg_table_group.js +++ b/src/ui/public/agg_table/agg_table_group.js @@ -28,10 +28,10 @@ uiModules if (!group || !group.tables.length) return; - let firstTable = group.tables[0]; - let params = firstTable.aggConfig && firstTable.aggConfig.params; + const firstTable = group.tables[0]; + const params = firstTable.aggConfig && firstTable.aggConfig.params; // render groups that have Table children as if they were rows, because iteration is cleaner - let childLayout = (params && !params.row) ? 'columns' : 'rows'; + const childLayout = (params && !params.row) ? 'columns' : 'rows'; $scope[childLayout] = group.tables; }); diff --git a/src/ui/public/agg_types/__tests__/agg_param_writer.js b/src/ui/public/agg_types/__tests__/agg_param_writer.js index 58d113f2e6c5c..0de3f8b1eb5b5 100644 --- a/src/ui/public/agg_types/__tests__/agg_param_writer.js +++ b/src/ui/public/agg_types/__tests__/agg_param_writer.js @@ -4,10 +4,10 @@ import AggTypesIndexProvider from 'ui/agg_types/index'; import RegistryVisTypesProvider from 'ui/registry/vis_types'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; module.exports = function AggParamWriterHelper(Private) { - let Vis = Private(VisProvider); - let aggTypes = Private(AggTypesIndexProvider); - let visTypes = Private(RegistryVisTypesProvider); - let stubbedLogstashIndexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const Vis = Private(VisProvider); + const aggTypes = Private(AggTypesIndexProvider); + const visTypes = Private(RegistryVisTypesProvider); + const stubbedLogstashIndexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); /** * Helper object for writing aggParams. Specify an aggType and it will find a vis & schema, and @@ -29,7 +29,7 @@ module.exports = function AggParamWriterHelper(Private) { * @param {string} opts.aggType - the name of the aggType we want to test. ('histogram', 'filter', etc.) */ function AggParamWriter(opts) { - let self = this; + const self = this; self.aggType = opts.aggType; if (_.isString(self.aggType)) { @@ -47,7 +47,7 @@ module.exports = function AggParamWriterHelper(Private) { // find a suitable vis type and schema _.find(visTypes, function (visType) { - let schema = _.find(visType.schemas.all, function (schema) { + const schema = _.find(visType.schemas.all, function (schema) { // type, type, type, type, type... :( return schema.group === self.aggType.type; }); @@ -69,7 +69,7 @@ module.exports = function AggParamWriterHelper(Private) { } AggParamWriter.prototype.write = function (paramValues) { - let self = this; + const self = this; paramValues = _.clone(paramValues); if (self.aggType.params.byName.field && !paramValues.field) { @@ -90,7 +90,7 @@ module.exports = function AggParamWriterHelper(Private) { }] }); - let aggConfig = _.find(self.vis.aggs, function (aggConfig) { + const aggConfig = _.find(self.vis.aggs, function (aggConfig) { return aggConfig.type === self.aggType; }); diff --git a/src/ui/public/agg_types/__tests__/agg_params.js b/src/ui/public/agg_types/__tests__/agg_params.js index 1eff825ecb769..84d06c6b6471e 100644 --- a/src/ui/public/agg_types/__tests__/agg_params.js +++ b/src/ui/public/agg_types/__tests__/agg_params.js @@ -28,11 +28,11 @@ describe('AggParams class', function () { describe('constructor args', function () { it('accepts an array of param defs', function () { - let params = [ + const params = [ { name: 'one' }, { name: 'two' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams).to.be.an(Array); @@ -42,43 +42,43 @@ describe('AggParams class', function () { describe('AggParam creation', function () { it('Uses the FieldAggParam class for params with the name "field"', function () { - let params = [ + const params = [ { name: 'field' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams[0]).to.be.a(FieldAggParam); }); it('Uses the OptionedAggParam class for params of type "optioned"', function () { - let params = [ + const params = [ { name: 'interval', type: 'optioned' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams[0]).to.be.a(OptionedAggParam); }); it('Uses the RegexAggParam class for params of type "regex"', function () { - let params = [ + const params = [ { name: 'exclude', type: 'regex' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(aggParams).to.have.length(params.length); expect(aggParams[0]).to.be.a(RegexAggParam); }); it('Always converts the params to a BaseAggParam', function () { - let params = [ + const params = [ { name: 'height', editor: 'high' @@ -92,7 +92,7 @@ describe('AggParams class', function () { editor: 'small' } ]; - let aggParams = new AggParams(params); + const aggParams = new AggParams(params); expect(BaseAggParam).to.have.property('callCount', params.length); expect(FieldAggParam).to.have.property('callCount', 0); diff --git a/src/ui/public/agg_types/__tests__/agg_type.js b/src/ui/public/agg_types/__tests__/agg_type.js index 94dbcab47d495..f8bb6616fe9aa 100644 --- a/src/ui/public/agg_types/__tests__/agg_type.js +++ b/src/ui/public/agg_types/__tests__/agg_type.js @@ -39,7 +39,7 @@ describe('AggType Class', function () { }); describe('application of config properties', function () { - let copiedConfigProps = [ + const copiedConfigProps = [ 'name', 'title', 'makeLabel', @@ -48,11 +48,11 @@ describe('AggType Class', function () { describe('"' + copiedConfigProps.join('", "') + '"', function () { it('assigns the config value to itself', function () { - let config = _.transform(copiedConfigProps, function (config, prop) { + const config = _.transform(copiedConfigProps, function (config, prop) { config[prop] = {}; }, {}); - let aggType = new AggType(config); + const aggType = new AggType(config); copiedConfigProps.forEach(function (prop) { expect(aggType[prop]).to.be(config[prop]); @@ -62,7 +62,7 @@ describe('AggType Class', function () { describe('makeLabel', function () { it('makes a function when the makeLabel config is not specified', function () { - let someGetter = function () {}; + const someGetter = function () {}; let aggType = new AggType({ makeLabel: someGetter @@ -81,7 +81,7 @@ describe('AggType Class', function () { describe('getFormat', function () { it('returns the formatter for the aggConfig', function () { - let aggType = new AggType({}); + const aggType = new AggType({}); let vis = new Vis(indexPattern, { type: 'histogram', @@ -112,9 +112,9 @@ describe('AggType Class', function () { }); it('can be overridden via config', function () { - let someGetter = function () {}; + const someGetter = function () {}; - let aggType = new AggType({ + const aggType = new AggType({ getFormat: someGetter }); @@ -128,7 +128,7 @@ describe('AggType Class', function () { }); it('defaults to AggParams object with JSON param', function () { - let aggType = new AggType({ + const aggType = new AggType({ name: 'smart agg' }); @@ -139,7 +139,7 @@ describe('AggType Class', function () { }); it('can disable customLabel', function () { - let aggType = new AggType({ + const aggType = new AggType({ name: 'smart agg', customLabels: false }); @@ -149,13 +149,13 @@ describe('AggType Class', function () { }); it('passes the params arg directly to the AggParams constructor', function () { - let params = [ + const params = [ {name: 'one'}, {name: 'two'} ]; - let paramLength = params.length + 2; // json and custom label are always appended + const paramLength = params.length + 2; // json and custom label are always appended - let aggType = new AggType({ + const aggType = new AggType({ name: 'bucketeer', params: params }); @@ -169,8 +169,8 @@ describe('AggType Class', function () { describe('getResponseAggs', function () { it('copies the value', function () { - let football = {}; - let aggType = new AggType({ + const football = {}; + const aggType = new AggType({ getResponseAggs: football }); @@ -178,7 +178,7 @@ describe('AggType Class', function () { }); it('defaults to _.noop', function () { - let aggType = new AggType({}); + const aggType = new AggType({}); expect(aggType.getResponseAggs).to.be(_.noop); }); diff --git a/src/ui/public/agg_types/__tests__/bucket_count_between.js b/src/ui/public/agg_types/__tests__/bucket_count_between.js index 75c2a4e46fdf7..61f0828f4b14f 100644 --- a/src/ui/public/agg_types/__tests__/bucket_count_between.js +++ b/src/ui/public/agg_types/__tests__/bucket_count_between.js @@ -32,7 +32,7 @@ describe('bucketCountBetween util', function () { })); it('returns a positive number when a is before b', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -46,14 +46,14 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.date_histogram[0]; - let b = vis.aggs.byTypeName.terms[0]; - let count = bucketCountBetween(a, b); + const a = vis.aggs.byTypeName.date_histogram[0]; + const b = vis.aggs.byTypeName.terms[0]; + const count = bucketCountBetween(a, b); expect(isNegative(count)).to.be(false); }); it('returns a negative number when a is after b', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -67,14 +67,14 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.terms[0]; - let b = vis.aggs.byTypeName.date_histogram[0]; - let count = bucketCountBetween(a, b); + const a = vis.aggs.byTypeName.terms[0]; + const b = vis.aggs.byTypeName.date_histogram[0]; + const count = bucketCountBetween(a, b); expect(isNegative(count)).to.be(true); }); it('returns 0 when there are no buckets between a and b', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -88,13 +88,13 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.date_histogram[0]; - let b = vis.aggs.byTypeName.terms[0]; + const a = vis.aggs.byTypeName.date_histogram[0]; + const b = vis.aggs.byTypeName.terms[0]; expect(bucketCountBetween(a, b)).to.be(0); }); it('returns null when b is not in the aggs', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -104,8 +104,8 @@ describe('bucketCountBetween util', function () { ] }); - let a = vis.aggs.byTypeName.date_histogram[0]; - let b = new AggConfig(vis, { + const a = vis.aggs.byTypeName.date_histogram[0]; + const b = new AggConfig(vis, { type: 'terms', schema: 'segment' }); @@ -114,7 +114,7 @@ describe('bucketCountBetween util', function () { }); it('returns null when a is not in the aggs', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -124,27 +124,27 @@ describe('bucketCountBetween util', function () { ] }); - let a = new AggConfig(vis, { + const a = new AggConfig(vis, { type: 'terms', schema: 'segment' }); - let b = vis.aggs.byTypeName.date_histogram[0]; + const b = vis.aggs.byTypeName.date_histogram[0]; expect(bucketCountBetween(a, b)).to.be(null); }); it('returns null when a and b are not in the aggs', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let a = new AggConfig(vis, { + const a = new AggConfig(vis, { type: 'terms', schema: 'segment' }); - let b = new AggConfig(vis, { + const b = new AggConfig(vis, { type: 'date_histogram', schema: 'segment' }); @@ -154,14 +154,14 @@ describe('bucketCountBetween util', function () { function countTest(pre, post) { return function () { - let schemas = visTypes.byName.histogram.schemas.buckets; + const schemas = visTypes.byName.histogram.schemas.buckets; // slow for this test is actually somewhere around 1/2 a sec this.slow(500); function randBucketAggForVis(vis) { - let schema = _.sample(schemas); - let aggType = _.sample(aggTypes.byType.buckets); + const schema = _.sample(schemas); + const aggType = _.sample(aggTypes.byType.buckets); return new AggConfig(vis, { schema: schema, @@ -170,18 +170,18 @@ describe('bucketCountBetween util', function () { } _.times(50, function (n) { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [] }); - let randBucketAgg = _.partial(randBucketAggForVis, vis); + const randBucketAgg = _.partial(randBucketAggForVis, vis); - let a = randBucketAgg(); - let b = randBucketAgg(); + const a = randBucketAgg(); + const b = randBucketAgg(); // create n aggs between a and b - let aggs = []; + const aggs = []; aggs.fill = function (n) { for (let i = 0; i < n; i++) { aggs.push(randBucketAgg()); diff --git a/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js b/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js index c4b2650cd6219..e0511b95f948c 100644 --- a/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js +++ b/src/ui/public/agg_types/__tests__/buckets/_geo_hash.js @@ -6,7 +6,7 @@ describe('Geohash Agg', function () { describe('write', function () { - let paramWriter = new AggTypesBucketsGeoHashProvider(function PrivateMock() { + const paramWriter = new AggTypesBucketsGeoHashProvider(function PrivateMock() { return function BucketMock(geohashProvider) { return geohashProvider.params[4]; }; diff --git a/src/ui/public/agg_types/__tests__/buckets/_histogram.js b/src/ui/public/agg_types/__tests__/buckets/_histogram.js index cf6f8d6ac86f9..a54f115ef1b71 100644 --- a/src/ui/public/agg_types/__tests__/buckets/_histogram.js +++ b/src/ui/public/agg_types/__tests__/buckets/_histogram.js @@ -28,7 +28,7 @@ describe('Histogram Agg', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private) { - let AggParamWriter = Private(AggParamWriterProvider); + const AggParamWriter = Private(AggParamWriterProvider); paramWriter = new AggParamWriter({ aggType: 'histogram' }); })); @@ -36,28 +36,28 @@ describe('Histogram Agg', function () { // reads aggConfig.params.interval, writes to dsl.interval it('accepts a whole number', function () { - let output = paramWriter.write({ interval: 100 }); + const output = paramWriter.write({ interval: 100 }); expect(output.params).to.have.property('interval', 100); }); it('accepts a decimal number', function () { - let output = paramWriter.write({ interval: 0.1 }); + const output = paramWriter.write({ interval: 0.1 }); expect(output.params).to.have.property('interval', 0.1); }); it('accepts a decimal number string', function () { - let output = paramWriter.write({ interval: '0.1' }); + const output = paramWriter.write({ interval: '0.1' }); expect(output.params).to.have.property('interval', 0.1); }); it('accepts a whole number string', function () { - let output = paramWriter.write({ interval: '10' }); + const output = paramWriter.write({ interval: '10' }); expect(output.params).to.have.property('interval', 10); }); it('fails on non-numeric values', function () { // template validation prevents this from users, not devs - let output = paramWriter.write({ interval: [] }); + const output = paramWriter.write({ interval: [] }); expect(isNaN(output.params.interval)).to.be.ok(); }); }); @@ -91,7 +91,7 @@ describe('Histogram Agg', function () { describe('extended_bounds', function () { it('writes when only eb.min is set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: { min: 0 } }); @@ -100,7 +100,7 @@ describe('Histogram Agg', function () { }); it('writes when only eb.max is set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: { max: 0 } }); @@ -109,7 +109,7 @@ describe('Histogram Agg', function () { }); it('writes when both eb.min and eb.max are set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: { min: 99, max: 100 } }); @@ -118,7 +118,7 @@ describe('Histogram Agg', function () { }); it('does not write when nothing is set', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: true, extended_bounds: {} }); @@ -126,7 +126,7 @@ describe('Histogram Agg', function () { }); it('does not write when min_doc_count is false', function () { - let output = paramWriter.write({ + const output = paramWriter.write({ min_doc_count: false, extended_bounds: { min: 99, max: 100 } }); diff --git a/src/ui/public/agg_types/__tests__/buckets/_range.js b/src/ui/public/agg_types/__tests__/buckets/_range.js index a25c447bdd38f..a9a5744250651 100644 --- a/src/ui/public/agg_types/__tests__/buckets/_range.js +++ b/src/ui/public/agg_types/__tests__/buckets/_range.js @@ -9,7 +9,7 @@ import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logsta import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; describe('Range Agg', function () { - let buckets = values(resp.aggregations[1].buckets); + const buckets = values(resp.aggregations[1].buckets); let range; let Vis; @@ -21,7 +21,7 @@ describe('Range Agg', function () { Vis = Private(VisProvider); indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let BytesFormat = Private(RegistryFieldFormatsProvider).byId.bytes; + const BytesFormat = Private(RegistryFieldFormatsProvider).byId.bytes; indexPattern.fieldFormatMap.bytes = new BytesFormat({ pattern: '0,0.[000] b' @@ -32,7 +32,7 @@ describe('Range Agg', function () { describe('formating', function () { it('formats bucket keys properly', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -49,8 +49,8 @@ describe('Range Agg', function () { ] }); - let agg = vis.aggs.byTypeName.range[0]; - let format = function (val) { + const agg = vis.aggs.byTypeName.range[0]; + const format = function (val) { return agg.fieldFormatter()(agg.getKey(val)); }; expect(format(buckets[0])).to.be('-∞ to 1 KB'); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js index 76daadfe70b4b..3982a6b37f459 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_histogram.js @@ -25,10 +25,10 @@ describe('AggConfig Filters', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private, $injector) { - let Vis = Private(VisProvider); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let createFilter = Private(AggTypesBucketsCreateFilterDateHistogramProvider); - let TimeBuckets = Private(TimeBucketsProvider); + const Vis = Private(VisProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const createFilter = Private(AggTypesBucketsCreateFilterDateHistogramProvider); + const TimeBuckets = Private(TimeBucketsProvider); intervalOptions = Private(AggTypesBucketsIntervalOptionsProvider); init = function (interval, duration) { @@ -51,7 +51,7 @@ describe('AggConfig Filters', function () { bucketKey = _.sample(aggResp.aggregations['1'].buckets).key; bucketStart = moment(bucketKey); - let timePad = moment.duration(duration / 2); + const timePad = moment.duration(duration / 2); agg.buckets.setBounds({ min: bucketStart.clone().subtract(timePad), max: bucketStart.clone().add(timePad), @@ -68,7 +68,7 @@ describe('AggConfig Filters', function () { expect(filter).to.have.property('range'); expect(filter.range).to.have.property(field.name); - let fieldParams = filter.range[field.name]; + const fieldParams = filter.range[field.name]; expect(fieldParams).to.have.property('gte'); expect(fieldParams.gte).to.be.a('number'); @@ -98,8 +98,8 @@ describe('AggConfig Filters', function () { init(option.val, duration); - let interval = agg.buckets.getInterval(); - let params = filter.range[field.name]; + const interval = agg.buckets.getInterval(); + const params = filter.range[field.name]; expect(params.gte).to.be(+bucketStart); expect(params.lt).to.be(+bucketStart.clone().add(interval)); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js index 117852228b6cc..5beaf4ba72409 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/date_range.js @@ -23,7 +23,7 @@ describe('AggConfig Filters', function () { })); it('should return a range filter for date_range agg', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -38,8 +38,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.date_range[0]; - let filter = createFilter(aggConfig, 'February 1st, 2015 to February 7th, 2015'); + const aggConfig = vis.aggs.byTypeName.date_range[0]; + const filter = createFilter(aggConfig, 'February 1st, 2015 to February 7th, 2015'); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js index 43069575965af..53c5e524f66b8 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/filters.js @@ -23,7 +23,7 @@ describe('AggConfig Filters', function () { })); it('should return a filters filter', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -39,8 +39,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.filters[0]; - let filter = createFilter(aggConfig, '_type:nginx'); + const aggConfig = vis.aggs.byTypeName.filters[0]; + const filter = createFilter(aggConfig, '_type:nginx'); expect(_.omit(filter, 'meta')).to.eql(aggConfig.params.filters[1].input); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js index 702cd0ea746b7..69af6d4a7cd48 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/histogram.js @@ -23,7 +23,7 @@ describe('AggConfig Filters', function () { })); it('should return an range filter for histogram', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -34,8 +34,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.histogram[0]; - let filter = createFilter(aggConfig, 2048); + const aggConfig = vis.aggs.byTypeName.histogram[0]; + const filter = createFilter(aggConfig, 2048); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); expect(filter).to.have.property('range'); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js index 2fb5708d57c9a..aa4177b6fa344 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/ip_range.js @@ -21,7 +21,7 @@ describe('AggConfig Filters', function () { })); it('should return a range filter for ip_range agg', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -40,8 +40,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.ip_range[0]; - let filter = createFilter(aggConfig, '0.0.0.0 to 1.1.1.1'); + const aggConfig = vis.aggs.byTypeName.ip_range[0]; + const filter = createFilter(aggConfig, '0.0.0.0 to 1.1.1.1'); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); @@ -51,7 +51,7 @@ describe('AggConfig Filters', function () { }); it('should return a range filter for ip_range agg using a CIDR mask', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -70,8 +70,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.ip_range[0]; - let filter = createFilter(aggConfig, '67.129.65.201/27'); + const aggConfig = vis.aggs.byTypeName.ip_range[0]; + const filter = createFilter(aggConfig, '67.129.65.201/27'); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js index b6ccd71d38cd5..023141bba6382 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/range.js @@ -21,7 +21,7 @@ describe('AggConfig Filters', function () { })); it('should return a range filter for range agg', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { @@ -37,8 +37,8 @@ describe('AggConfig Filters', function () { ] }); - let aggConfig = vis.aggs.byTypeName.range[0]; - let filter = createFilter(aggConfig, { gte: 1024, lt: 2048.0 }); + const aggConfig = vis.aggs.byTypeName.range[0]; + const filter = createFilter(aggConfig, { gte: 1024, lt: 2048.0 }); expect(filter).to.have.property('range'); expect(filter).to.have.property('meta'); expect(filter.meta).to.have.property('index', indexPattern.id); diff --git a/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js b/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js index c0a67aa283655..50056b516d42e 100644 --- a/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js +++ b/src/ui/public/agg_types/__tests__/buckets/create_filter/terms.js @@ -21,12 +21,12 @@ describe('AggConfig Filters', function () { })); it('should return a match filter for terms', function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'terms', schema: 'segment', params: { field: '_type' } } ] }); - let aggConfig = vis.aggs.byTypeName.terms[0]; - let filter = createFilter(aggConfig, 'apache'); + const aggConfig = vis.aggs.byTypeName.terms[0]; + const filter = createFilter(aggConfig, 'apache'); expect(filter).to.have.property('query'); expect(filter.query).to.have.property('match'); expect(filter.query.match).to.have.property('_type'); diff --git a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js index 6d2e4834418eb..62bc7944e747b 100644 --- a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js +++ b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_editor.js @@ -17,7 +17,7 @@ describe('editor', function () { beforeEach(ngMock.inject(function (Private, $injector, $compile) { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let Vis = Private(VisProvider); + const Vis = Private(VisProvider); /** * Render the AggParams editor for the date histogram aggregation @@ -38,8 +38,8 @@ describe('editor', function () { ] }); - let $el = $(''); - let $parentScope = $injector.get('$rootScope').$new(); + const $el = $(''); + const $parentScope = $injector.get('$rootScope').$new(); agg = $parentScope.agg = vis.aggs.bySchemaName.segment[0]; $parentScope.groupName = 'buckets'; @@ -48,10 +48,10 @@ describe('editor', function () { $scope = $el.scope(); $scope.$digest(); - let $inputs = $('vis-agg-param-editor', $el); + const $inputs = $('vis-agg-param-editor', $el); return _.transform($inputs.toArray(), function (inputs, e) { - let $el = $(e); - let $scope = $el.scope(); + const $el = $(e); + const $scope = $el.scope(); inputs[$scope.aggParam.name] = { $el: $el, @@ -107,7 +107,7 @@ describe('editor', function () { expect(params.interval.modelValue().val).to.be('auto'); expect(params.field.modelValue().name).to.be(indexPattern.timeFieldName); - let field = _.find(indexPattern.fields, function (f) { + const field = _.find(indexPattern.fields, function (f) { return f.type === 'date' && f.name !== indexPattern.timeFieldName; }); diff --git a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js index 4e6c6870f2574..5a0c06d6811b3 100644 --- a/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js +++ b/src/ui/public/agg_types/__tests__/buckets/date_histogram/_params.js @@ -18,9 +18,9 @@ describe('params', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private, $injector) { - let AggParamWriter = Private(AggParamWriterProvider); - let indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - let timefilter = $injector.get('timefilter'); + const AggParamWriter = Private(AggParamWriterProvider); + const indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + const timefilter = $injector.get('timefilter'); timeField = indexPattern.timeFieldName; aggTypes = Private(AggTypesIndexProvider); @@ -31,7 +31,7 @@ describe('params', function () { return paramWriter.write({ interval: interval, field: timeField }); }; - let now = moment(); + const now = moment(); setTimeBounds = function (n, units) { timefilter.enabled = true; timefilter.getBounds = _.constant({ @@ -43,24 +43,24 @@ describe('params', function () { describe('interval', function () { it('accepts a valid interval', function () { - let output = writeInterval('d'); + const output = writeInterval('d'); expect(output.params).to.have.property('interval', '1d'); }); it('ignores invalid intervals', function () { - let output = writeInterval('foo'); + const output = writeInterval('foo'); expect(output.params).to.have.property('interval', '0ms'); }); it('automatically picks an interval', function () { setTimeBounds(15, 'm'); - let output = writeInterval('auto'); + const output = writeInterval('auto'); expect(output.params.interval).to.be('30s'); }); it('scales up the interval if it will make too many buckets', function () { setTimeBounds(30, 'm'); - let output = writeInterval('s'); + const output = writeInterval('s'); expect(output.params.interval).to.be('10s'); expect(output.metricScaleText).to.be('second'); expect(output.metricScale).to.be(0.1); @@ -68,30 +68,30 @@ describe('params', function () { it('does not scale down the interval', function () { setTimeBounds(1, 'm'); - let output = writeInterval('h'); + const output = writeInterval('h'); expect(output.params.interval).to.be('1h'); expect(output.metricScaleText).to.be(undefined); expect(output.metricScale).to.be(undefined); }); describe('only scales when all metrics are sum or count', function () { - let tests = [ + const tests = [ [ false, 'avg', 'count', 'sum' ], [ true, 'count', 'sum' ], [ false, 'count', 'cardinality' ] ]; tests.forEach(function (test) { - let should = test.shift(); - let typeNames = test.slice(); + const should = test.shift(); + const typeNames = test.slice(); it(typeNames.join(', ') + ' should ' + (should ? '' : 'not') + ' scale', function () { setTimeBounds(1, 'y'); - let vis = paramWriter.vis; + const vis = paramWriter.vis; vis.aggs.splice(0); - let histoConfig = new AggConfig(vis, { + const histoConfig = new AggConfig(vis, { type: aggTypes.byName.date_histogram, schema: 'segment', params: { interval: 's', field: timeField } @@ -106,7 +106,7 @@ describe('params', function () { })); }); - let output = histoConfig.write(); + const output = histoConfig.write(); expect(_.has(output, 'metricScale')).to.be(should); }); }); @@ -115,9 +115,9 @@ describe('params', function () { describe('extended_bounds', function () { it('should write a long value if a moment passed in', function () { - let then = moment(0); - let now = moment(500); - let output = paramWriter.write({ + const then = moment(0); + const now = moment(500); + const output = paramWriter.write({ extended_bounds: { min: then, max: now @@ -133,9 +133,9 @@ describe('params', function () { }); it('should write a long if a long is passed', function () { - let then = 0; - let now = 500; - let output = paramWriter.write({ + const then = 0; + const now = 500; + const output = paramWriter.write({ extended_bounds: { min: then, max: now diff --git a/src/ui/public/agg_types/__tests__/controls/number_list.js b/src/ui/public/agg_types/__tests__/controls/number_list.js index 3c7204b0682b8..121501dcbfd7b 100644 --- a/src/ui/public/agg_types/__tests__/controls/number_list.js +++ b/src/ui/public/agg_types/__tests__/controls/number_list.js @@ -13,15 +13,15 @@ describe('NumberList directive', function () { function onlyValidValues() { return $el.find('[ng-model]').toArray().map(function (el) { - let ngModel = $(el).controller('ngModel'); + const ngModel = $(el).controller('ngModel'); return ngModel.$valid ? ngModel.$modelValue : undefined; }); } beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function ($injector) { - let $compile = $injector.get('$compile'); - let $rootScope = $injector.get('$rootScope'); + const $compile = $injector.get('$compile'); + const $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $el = $(''); @@ -75,7 +75,7 @@ describe('NumberList directive', function () { it('shift-up increases by 0.1', function () { compile([4.8]); - let seq = [ + const seq = [ { type: 'press', key: 'shift', @@ -111,7 +111,7 @@ describe('NumberList directive', function () { it('shift-down decreases by 0.1', function () { compile([5.1]); - let seq = [ + const seq = [ { type: 'press', key: 'shift', @@ -135,12 +135,12 @@ describe('NumberList directive', function () { it('maintains valid number', function () { compile([9, 11, 13]); - let seq = [ + const seq = [ 'down', // 10 (11 - 1) 'down' // 10 (limited by 9) ]; - let getEl = function () { return $el.find('input').eq(1); }; + const getEl = function () { return $el.find('input').eq(1); }; return simulateKeys(getEl, seq) .then(function () { diff --git a/src/ui/public/agg_types/__tests__/metrics/median.js b/src/ui/public/agg_types/__tests__/metrics/median.js index 3524031c62029..81589c4bf6f48 100644 --- a/src/ui/public/agg_types/__tests__/metrics/median.js +++ b/src/ui/public/agg_types/__tests__/metrics/median.js @@ -17,7 +17,7 @@ describe('AggTypeMetricMedianProvider class', function () { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); aggTypeMetricMedian = Private(AggTypeMetricMedianProvider); - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { 'title': 'New Visualization', 'type': 'metric', 'params': { @@ -42,7 +42,7 @@ describe('AggTypeMetricMedianProvider class', function () { // Grab the aggConfig off the vis (we don't actually use the vis for // anything else) - let aggConfig = vis.aggs[0]; + const aggConfig = vis.aggs[0]; aggDsl = aggConfig.toDsl(); })); diff --git a/src/ui/public/agg_types/__tests__/metrics/std_deviation.js b/src/ui/public/agg_types/__tests__/metrics/std_deviation.js index 90666b65e5dbd..1433ed793ccaa 100644 --- a/src/ui/public/agg_types/__tests__/metrics/std_deviation.js +++ b/src/ui/public/agg_types/__tests__/metrics/std_deviation.js @@ -18,37 +18,37 @@ describe('AggTypeMetricStandardDeviationProvider class', function () { })); it('uses the custom label if it is set', function () { - let vis = new Vis(indexPattern, {}); + const vis = new Vis(indexPattern, {}); // Grab the aggConfig off the vis (we don't actually use the vis for // anything else) - let aggConfig = vis.aggs[0]; + const aggConfig = vis.aggs[0]; aggConfig.params.customLabel = 'custom label'; aggConfig.params.field = { displayName: 'memory' }; - let responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); - let lowerStdDevLabel = responseAggs[0].makeLabel(); - let upperStdDevLabel = responseAggs[1].makeLabel(); + const responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); + const lowerStdDevLabel = responseAggs[0].makeLabel(); + const upperStdDevLabel = responseAggs[1].makeLabel(); expect(lowerStdDevLabel).to.be('Lower custom label'); expect(upperStdDevLabel).to.be('Upper custom label'); }); it('uses the default labels if custom label is not set', function () { - let vis = new Vis(indexPattern, {}); + const vis = new Vis(indexPattern, {}); // Grab the aggConfig off the vis (we don't actually use the vis for // anything else) - let aggConfig = vis.aggs[0]; + const aggConfig = vis.aggs[0]; aggConfig.params.field = { displayName: 'memory' }; - let responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); - let lowerStdDevLabel = responseAggs[0].makeLabel(); - let upperStdDevLabel = responseAggs[1].makeLabel(); + const responseAggs = aggTypeMetricStandardDeviation.getResponseAggs(aggConfig); + const lowerStdDevLabel = responseAggs[0].makeLabel(); + const upperStdDevLabel = responseAggs[1].makeLabel(); expect(lowerStdDevLabel).to.be('Lower Standard Deviation of memory'); expect(upperStdDevLabel).to.be('Upper Standard Deviation of memory'); diff --git a/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js b/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js index 47455e418a38a..df28b1a06b2d4 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js +++ b/src/ui/public/agg_types/__tests__/param_types/_calculate_interval.js @@ -21,15 +21,15 @@ describe('calculateInterval()', function () { calculateInterval = Private(AggTypesParamTypesCalculateIntervalProvider); })); - let testInterval = function (option, expected) { - let msg = 'should return ' + JSON.stringify(expected) + ' for ' + option; + const testInterval = function (option, expected) { + const msg = 'should return ' + JSON.stringify(expected) + ' for ' + option; it(msg, function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'histogram', aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp', interval: option } } ] }); - let aggConfig = vis.aggs.byTypeName.date_histogram[0]; - let interval = calculateInterval(aggConfig); + const aggConfig = vis.aggs.byTypeName.date_histogram[0]; + const interval = calculateInterval(aggConfig); _.each(expected, function (val, key) { expect(interval).to.have.property(key, val); }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_field.js b/src/ui/public/agg_types/__tests__/param_types/_field.js index cc2679fc0d4b8..cf9927ef19ffa 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_field.js +++ b/src/ui/public/agg_types/__tests__/param_types/_field.js @@ -17,7 +17,7 @@ describe('Field', function () { describe('constructor', function () { it('it is an instance of BaseAggParam', function () { - let aggParam = new FieldAggParam({ + const aggParam = new FieldAggParam({ name: 'field' }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_optioned.js b/src/ui/public/agg_types/__tests__/param_types/_optioned.js index 69165309fb12d..ad6db067548de 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_optioned.js +++ b/src/ui/public/agg_types/__tests__/param_types/_optioned.js @@ -17,7 +17,7 @@ describe('Optioned', function () { describe('constructor', function () { it('it is an instance of BaseAggParam', function () { - let aggParam = new OptionedAggParam({ + const aggParam = new OptionedAggParam({ name: 'some_param', type: 'optioned' }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_raw_json.js b/src/ui/public/agg_types/__tests__/param_types/_raw_json.js index 86c69ee620dad..53bfd8b8a5a8f 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_raw_json.js +++ b/src/ui/public/agg_types/__tests__/param_types/_raw_json.js @@ -6,7 +6,7 @@ import AggTypesParamTypesRawJsonProvider from 'ui/agg_types/param_types/raw_json module.exports = describe('JSON', function () { - let paramName = 'json_test'; + const paramName = 'json_test'; let BaseAggParam; let JsonAggParam; let aggParam; @@ -15,7 +15,7 @@ module.exports = describe('JSON', function () { function initAggParam(config) { config = config || {}; - let defaults = { + const defaults = { name: paramName, type: 'json' }; @@ -59,7 +59,7 @@ module.exports = describe('JSON', function () { }); it('should append param when valid JSON', function () { - let jsonData = JSON.stringify({ + const jsonData = JSON.stringify({ new_param: 'should exist in output' }); @@ -75,7 +75,7 @@ module.exports = describe('JSON', function () { }); it('should not overwrite existing params', function () { - let jsonData = JSON.stringify({ + const jsonData = JSON.stringify({ new_param: 'should exist in output', existing: 'should be used' }); @@ -88,7 +88,7 @@ module.exports = describe('JSON', function () { }); it('should drop nulled params', function () { - let jsonData = JSON.stringify({ + const jsonData = JSON.stringify({ new_param: 'should exist in output', field: null }); diff --git a/src/ui/public/agg_types/__tests__/param_types/_regex.js b/src/ui/public/agg_types/__tests__/param_types/_regex.js index a29c7b7d812e3..d426da4d40db2 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_regex.js +++ b/src/ui/public/agg_types/__tests__/param_types/_regex.js @@ -23,7 +23,7 @@ describe('Regex', function () { describe('constructor', function () { it('should be an instance of BaseAggParam', function () { - let aggParam = new RegexAggParam({ + const aggParam = new RegexAggParam({ name: 'some_param', type: 'regex' }); @@ -36,11 +36,11 @@ describe('Regex', function () { describe('write results', function () { let aggParam; let aggConfig; - let output = { params: {} }; - let paramName = 'exclude'; + const output = { params: {} }; + const paramName = 'exclude'; beforeEach(function () { - let vis = new Vis(indexPattern, { + const vis = new Vis(indexPattern, { type: 'pie', aggs: [ { type: 'terms', schema: 'split', params: { field: 'extension' }}, diff --git a/src/ui/public/agg_types/__tests__/param_types/_string.js b/src/ui/public/agg_types/__tests__/param_types/_string.js index fde04e53a2742..01de3883c115c 100644 --- a/src/ui/public/agg_types/__tests__/param_types/_string.js +++ b/src/ui/public/agg_types/__tests__/param_types/_string.js @@ -5,7 +5,7 @@ import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; import AggTypesParamTypesStringProvider from 'ui/agg_types/param_types/string'; module.exports = describe('String', function () { - let paramName = 'json_test'; + const paramName = 'json_test'; let BaseAggParam; let StringAggParam; let aggParam; @@ -14,7 +14,7 @@ module.exports = describe('String', function () { function initAggParam(config) { config = config || {}; - let defaults = { + const defaults = { name: paramName, type: 'string' }; @@ -42,8 +42,8 @@ module.exports = describe('String', function () { describe('write', function () { it('should append param by name', function () { - let paramName = 'testing'; - let params = {}; + const paramName = 'testing'; + const params = {}; params[paramName] = 'some input'; initAggParam({ name: paramName }); @@ -55,8 +55,8 @@ module.exports = describe('String', function () { }); it('should not be in output with empty input', function () { - let paramName = 'more_testing'; - let params = {}; + const paramName = 'more_testing'; + const params = {}; params[paramName] = ''; initAggParam({ name: paramName }); diff --git a/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js b/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js index c12ced529cf5f..8fdab2c7c66ad 100644 --- a/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js +++ b/src/ui/public/agg_types/__tests__/utils/_stub_agg_params.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import sinon from 'auto-release-sinon'; function ParamClassStub(parent, body) { - let stub = sinon.spy(body || function () { + const stub = sinon.spy(body || function () { stub.Super && stub.Super.call(this); }); if (parent) _.class(stub).inherits(parent); @@ -24,7 +24,7 @@ function ParamClassStub(parent, body) { * @return {undefined} */ module.exports = function stubParamClasses(Private) { - let BaseAggParam = Private.stub( + const BaseAggParam = Private.stub( require('ui/agg_types/param_types/base'), new ParamClassStub(null, function (config) { _.assign(this, config); diff --git a/src/ui/public/agg_types/agg_params.js b/src/ui/public/agg_types/agg_params.js index d6c435c214b4c..22e85cf12a73a 100644 --- a/src/ui/public/agg_types/agg_params.js +++ b/src/ui/public/agg_types/agg_params.js @@ -10,7 +10,7 @@ import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function AggParamsFactory(Private) { - let paramTypeMap = { + const paramTypeMap = { field: Private(AggTypesParamTypesFieldProvider), optioned: Private(AggTypesParamTypesOptionedProvider), regex: Private(AggTypesParamTypesRegexProvider), @@ -37,8 +37,8 @@ export default function AggParamsFactory(Private) { AggParams.Super.call(this, { index: ['name'], initialSet: params.map(function (config) { - let type = config.name === 'field' ? config.name : config.type; - let Class = paramTypeMap[type] || paramTypeMap._default; + const type = config.name === 'field' ? config.name : config.type; + const Class = paramTypeMap[type] || paramTypeMap._default; return new Class(config); }) }); @@ -59,7 +59,7 @@ export default function AggParamsFactory(Private) { * are dependent on the AggParam#write methods which should be studied for each AggType. */ AggParams.prototype.write = function (aggConfig, locals) { - let output = { params: {} }; + const output = { params: {} }; locals = locals || {}; this.forEach(function (param) { diff --git a/src/ui/public/agg_types/agg_type.js b/src/ui/public/agg_types/agg_type.js index f73b15cac7acc..303f1c14cbb16 100644 --- a/src/ui/public/agg_types/agg_type.js +++ b/src/ui/public/agg_types/agg_type.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import AggTypesAggParamsProvider from 'ui/agg_types/agg_params'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function AggTypeFactory(Private) { - let AggParams = Private(AggTypesAggParamsProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const AggParams = Private(AggTypesAggParamsProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); /** * Generic AggType Constructor @@ -142,7 +142,7 @@ export default function AggTypeFactory(Private) { * @return {FieldFromat} */ AggType.prototype.getFormat = function (agg) { - let field = agg.getField(); + const field = agg.getField(); return field ? field.format : fieldFormats.getDefaultInstance('string'); }; diff --git a/src/ui/public/agg_types/buckets/_bucket_agg_type.js b/src/ui/public/agg_types/buckets/_bucket_agg_type.js index 4249ec29be71e..7f125455906e9 100644 --- a/src/ui/public/agg_types/buckets/_bucket_agg_type.js +++ b/src/ui/public/agg_types/buckets/_bucket_agg_type.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import AggTypesAggTypeProvider from 'ui/agg_types/agg_type'; export default function BucketAggTypeProvider(Private) { - let AggType = Private(AggTypesAggTypeProvider); + const AggType = Private(AggTypesAggTypeProvider); _.class(BucketAggType).inherits(AggType); function BucketAggType(config) { diff --git a/src/ui/public/agg_types/buckets/_bucket_count_between.js b/src/ui/public/agg_types/buckets/_bucket_count_between.js index 3fbcd3e723343..2838c8397b8e9 100644 --- a/src/ui/public/agg_types/buckets/_bucket_count_between.js +++ b/src/ui/public/agg_types/buckets/_bucket_count_between.js @@ -13,19 +13,19 @@ export default function BucketCountBetweenProvider() { * @return {null|number} */ function bucketCountBetween(aggConfigA, aggConfigB) { - let aggs = aggConfigA.vis.aggs.getRequestAggs(); + const aggs = aggConfigA.vis.aggs.getRequestAggs(); - let aIndex = aggs.indexOf(aggConfigA); - let bIndex = aggs.indexOf(aggConfigB); + const aIndex = aggs.indexOf(aggConfigA); + const bIndex = aggs.indexOf(aggConfigB); if (aIndex === -1 || bIndex === -1) { return null; } // return a negative distance, if b is before a - let negative = (aIndex > bIndex); + const negative = (aIndex > bIndex); - let count = aggs + const count = aggs .slice(Math.min(aIndex, bIndex), Math.max(aIndex, bIndex)) .reduce(function (count, cfg) { if (cfg === aggConfigA || cfg === aggConfigB || cfg.schema.group !== 'buckets') { diff --git a/src/ui/public/agg_types/buckets/_interval_options.js b/src/ui/public/agg_types/buckets/_interval_options.js index 344b7fa30b2c9..9273a9663566f 100644 --- a/src/ui/public/agg_types/buckets/_interval_options.js +++ b/src/ui/public/agg_types/buckets/_interval_options.js @@ -3,7 +3,7 @@ import moment from 'moment'; export default function IntervalOptionsService(Private) { // shorthand - let ms = function (type) { return moment.duration(1, type).asMilliseconds(); }; + const ms = function (type) { return moment.duration(1, type).asMilliseconds(); }; return [ { diff --git a/src/ui/public/agg_types/buckets/create_filter/date_histogram.js b/src/ui/public/agg_types/buckets/create_filter/date_histogram.js index 67b23bbf2e945..2e3f1dc1f0464 100644 --- a/src/ui/public/agg_types/buckets/create_filter/date_histogram.js +++ b/src/ui/public/agg_types/buckets/create_filter/date_histogram.js @@ -3,8 +3,8 @@ import buildRangeFilter from 'ui/filter_manager/lib/range'; export default function createDateHistogramFilterProvider(Private) { return function (agg, key) { - let start = moment(key); - let interval = agg.buckets.getInterval(); + const start = moment(key); + const interval = agg.buckets.getInterval(); return buildRangeFilter(agg.params.field, { gte: start.valueOf(), diff --git a/src/ui/public/agg_types/buckets/create_filter/date_range.js b/src/ui/public/agg_types/buckets/create_filter/date_range.js index 89e8232b6e53e..ac44be29de4b7 100644 --- a/src/ui/public/agg_types/buckets/create_filter/date_range.js +++ b/src/ui/public/agg_types/buckets/create_filter/date_range.js @@ -4,9 +4,9 @@ import buildRangeFilter from 'ui/filter_manager/lib/range'; export default function createDateRangeFilterProvider(config) { return function (agg, key) { - let range = dateRange.parse(key, config.get('dateFormat')); + const range = dateRange.parse(key, config.get('dateFormat')); - let filter = {}; + const filter = {}; if (range.from) filter.gte = +range.from; if (range.to) filter.lt = +range.to; if (range.to && range.from) filter.format = 'epoch_millis'; diff --git a/src/ui/public/agg_types/buckets/create_filter/filters.js b/src/ui/public/agg_types/buckets/create_filter/filters.js index e9cbde979f2f8..da1726ffbf330 100644 --- a/src/ui/public/agg_types/buckets/create_filter/filters.js +++ b/src/ui/public/agg_types/buckets/create_filter/filters.js @@ -3,8 +3,8 @@ import _ from 'lodash'; export default function CreateFilterFiltersProvider(Private) { return function (aggConfig, key) { // have the aggConfig write agg dsl params - let dslFilters = _.get(aggConfig.toDsl(), 'filters.filters'); - let filter = dslFilters[key]; + const dslFilters = _.get(aggConfig.toDsl(), 'filters.filters'); + const filter = dslFilters[key]; if (filter) { return buildQueryFilter(filter.query, aggConfig.vis.indexPattern.id); diff --git a/src/ui/public/agg_types/buckets/create_filter/histogram.js b/src/ui/public/agg_types/buckets/create_filter/histogram.js index fd6c8c1e21c16..30c828b7a4567 100644 --- a/src/ui/public/agg_types/buckets/create_filter/histogram.js +++ b/src/ui/public/agg_types/buckets/create_filter/histogram.js @@ -2,7 +2,7 @@ import buildRangeFilter from 'ui/filter_manager/lib/range'; export default function createHistogramFilterProvider(Private) { return function (aggConfig, key) { - let value = parseInt(key, 10); + const value = parseInt(key, 10); return buildRangeFilter( aggConfig.params.field, diff --git a/src/ui/public/agg_types/buckets/date_range.js b/src/ui/public/agg_types/buckets/date_range.js index bd265516df7c1..7798b759a68db 100644 --- a/src/ui/public/agg_types/buckets/date_range.js +++ b/src/ui/public/agg_types/buckets/date_range.js @@ -7,9 +7,9 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import dateRangesTemplate from 'ui/agg_types/controls/date_ranges.html'; export default function DateRangeAggDefinition(Private, config) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterDateRangeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterDateRangeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); return new BucketAggType({ @@ -17,7 +17,7 @@ export default function DateRangeAggDefinition(Private, config) { title: 'Date Range', createFilter: createFilter, getKey: function (bucket, key, agg) { - let formatter = agg.fieldOwnFormatter('text', fieldFormats.getDefaultInstance('date')); + const formatter = agg.fieldOwnFormatter('text', fieldFormats.getDefaultInstance('date')); return dateRange.toString(bucket, formatter); }, getFormat: function () { diff --git a/src/ui/public/agg_types/buckets/filters.js b/src/ui/public/agg_types/buckets/filters.js index 47ab9c13bd0c7..85ad336b4c023 100644 --- a/src/ui/public/agg_types/buckets/filters.js +++ b/src/ui/public/agg_types/buckets/filters.js @@ -5,10 +5,10 @@ import AggTypesBucketsCreateFilterFiltersProvider from 'ui/agg_types/buckets/cre import DecorateQueryProvider from 'ui/courier/data_source/_decorate_query'; import filtersTemplate from 'ui/agg_types/controls/filters.html'; export default function FiltersAggDefinition(Private, Notifier) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterFiltersProvider); - let decorateQuery = Private(DecorateQueryProvider); - let notif = new Notifier({ location: 'Filters Agg' }); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterFiltersProvider); + const decorateQuery = Private(DecorateQueryProvider); + const notif = new Notifier({ location: 'Filters Agg' }); return new BucketAggType({ name: 'filters', @@ -21,25 +21,25 @@ export default function FiltersAggDefinition(Private, Notifier) { editor: filtersTemplate, default: [ {input: {}, label: ''} ], write: function (aggConfig, output) { - let inFilters = aggConfig.params.filters; + const inFilters = aggConfig.params.filters; if (!_.size(inFilters)) return; - let outFilters = _.transform(inFilters, function (filters, filter) { - let input = filter.input; + const outFilters = _.transform(inFilters, function (filters, filter) { + const input = filter.input; if (!input) return notif.log('malformed filter agg params, missing "input" query'); - let query = input.query; + const query = input.query; if (!query) return notif.log('malformed filter agg params, missing "query" on input'); decorateQuery(query); - let label = filter.label || _.get(query, 'query_string.query') || angular.toJson(query); + const label = filter.label || _.get(query, 'query_string.query') || angular.toJson(query); filters[label] = input; }, {}); if (!_.size(outFilters)) return; - let params = output.params || (output.params = {}); + const params = output.params || (output.params = {}); params.filters = outFilters; } } diff --git a/src/ui/public/agg_types/buckets/geo_hash.js b/src/ui/public/agg_types/buckets/geo_hash.js index 230683f4514a2..14c58da476003 100644 --- a/src/ui/public/agg_types/buckets/geo_hash.js +++ b/src/ui/public/agg_types/buckets/geo_hash.js @@ -11,7 +11,7 @@ export default function GeoHashAggDefinition(Private, config) { * Map Leaflet zoom levels to geohash precision levels. * The size of a geohash column-width on the map should be at least `minGeohashPixels` pixels wide. */ - let zoomPrecision = {}; + const zoomPrecision = {}; const minGeohashPixels = 16; for (let zoom = 0; zoom <= 21; zoom += 1) { const worldPixels = 256 * Math.pow(2, zoom); diff --git a/src/ui/public/agg_types/buckets/histogram.js b/src/ui/public/agg_types/buckets/histogram.js index 8ebffb710e4ea..95f87bd607ee8 100644 --- a/src/ui/public/agg_types/buckets/histogram.js +++ b/src/ui/public/agg_types/buckets/histogram.js @@ -7,8 +7,8 @@ import intervalTemplate from 'ui/agg_types/controls/interval.html'; import minDocCountTemplate from 'ui/agg_types/controls/min_doc_count.html'; import extendedBoundsTemplate from 'ui/agg_types/controls/extended_bounds.html'; export default function HistogramAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterHistogramProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterHistogramProvider); return new BucketAggType({ @@ -51,7 +51,7 @@ export default function HistogramAggDefinition(Private) { default: {}, editor: extendedBoundsTemplate, write: function (aggConfig, output) { - let val = aggConfig.params.extended_bounds; + const val = aggConfig.params.extended_bounds; if (aggConfig.params.min_doc_count && (val.min != null || val.max != null)) { output.params.extended_bounds = { @@ -63,7 +63,7 @@ export default function HistogramAggDefinition(Private) { // called from the editor shouldShow: function (aggConfig) { - let field = aggConfig.params.field; + const field = aggConfig.params.field; if ( field && (field.type === 'number' || field.type === 'date') diff --git a/src/ui/public/agg_types/buckets/ip_range.js b/src/ui/public/agg_types/buckets/ip_range.js index 82a9c8776d46c..9fa7c367c2175 100644 --- a/src/ui/public/agg_types/buckets/ip_range.js +++ b/src/ui/public/agg_types/buckets/ip_range.js @@ -6,8 +6,8 @@ import AggTypesBucketsCreateFilterIpRangeProvider from 'ui/agg_types/buckets/cre import ipRangesTemplate from 'ui/agg_types/controls/ip_ranges.html'; export default function RangeAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterIpRangeProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterIpRangeProvider); return new BucketAggType({ name: 'ip_range', diff --git a/src/ui/public/agg_types/buckets/range.js b/src/ui/public/agg_types/buckets/range.js index 446cae17dc176..f89ddec330d77 100644 --- a/src/ui/public/agg_types/buckets/range.js +++ b/src/ui/public/agg_types/buckets/range.js @@ -5,13 +5,13 @@ import IndexPatternsFieldFormatFieldFormatProvider from 'ui/index_patterns/_fiel import RangeKeyProvider from './range_key'; import rangesTemplate from 'ui/agg_types/controls/ranges.html'; export default function RangeAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterRangeProvider); - let FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); - let RangeKey = Private(RangeKeyProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterRangeProvider); + const FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); + const RangeKey = Private(RangeKeyProvider); - let keyCaches = new WeakMap(); - let formats = new WeakMap(); + const keyCaches = new WeakMap(); + const formats = new WeakMap(); return new BucketAggType({ name: 'range', @@ -28,7 +28,7 @@ export default function RangeAggDefinition(Private) { keyCaches.set(agg, keys); } - let id = RangeKey.idBucket(bucket); + const id = RangeKey.idBucket(bucket); key = keys.get(id); if (!key) { @@ -42,8 +42,8 @@ export default function RangeAggDefinition(Private) { let format = formats.get(agg); if (format) return format; - let RangeFormat = FieldFormat.from(function (range) { - let format = agg.fieldOwnFormatter(); + const RangeFormat = FieldFormat.from(function (range) { + const format = agg.fieldOwnFormatter(); return `${format(range.gte)} to ${format(range.lt)}`; }); diff --git a/src/ui/public/agg_types/buckets/significant_terms.js b/src/ui/public/agg_types/buckets/significant_terms.js index 789df97ff00cf..30e339471b869 100644 --- a/src/ui/public/agg_types/buckets/significant_terms.js +++ b/src/ui/public/agg_types/buckets/significant_terms.js @@ -3,8 +3,8 @@ import AggTypesBucketsBucketAggTypeProvider from 'ui/agg_types/buckets/_bucket_a import AggTypesBucketsCreateFilterTermsProvider from 'ui/agg_types/buckets/create_filter/terms'; import orderAndSizeTemplate from 'ui/agg_types/controls/order_and_size.html'; export default function SignificantTermsAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); return new BucketAggType({ name: 'significant_terms', diff --git a/src/ui/public/agg_types/buckets/terms.js b/src/ui/public/agg_types/buckets/terms.js index 1a326ec8e8e81..4d76806106b69 100644 --- a/src/ui/public/agg_types/buckets/terms.js +++ b/src/ui/public/agg_types/buckets/terms.js @@ -9,14 +9,14 @@ import orderAndSizeTemplate from 'ui/agg_types/controls/order_and_size.html'; import routeBasedNotifierProvider from 'ui/route_based_notifier'; export default function TermsAggDefinition(Private) { - let BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); - let bucketCountBetween = Private(AggTypesBucketsBucketCountBetweenProvider); - let AggConfig = Private(VisAggConfigProvider); - let Schemas = Private(VisSchemasProvider); - let createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); + const BucketAggType = Private(AggTypesBucketsBucketAggTypeProvider); + const bucketCountBetween = Private(AggTypesBucketsBucketCountBetweenProvider); + const AggConfig = Private(VisAggConfigProvider); + const Schemas = Private(VisSchemasProvider); + const createFilter = Private(AggTypesBucketsCreateFilterTermsProvider); const routeBasedNotifier = Private(routeBasedNotifierProvider); - let orderAggSchema = (new Schemas([ + const orderAggSchema = (new Schemas([ { group: 'none', name: 'orderAgg', @@ -27,7 +27,7 @@ export default function TermsAggDefinition(Private) { function isNotType(type) { return function (agg) { - let field = agg.params.field; + const field = agg.params.field; return !field || field.type !== type; }; } @@ -36,7 +36,7 @@ export default function TermsAggDefinition(Private) { name: 'terms', title: 'Terms', makeLabel: function (agg) { - let params = agg.params; + const params = agg.params; return agg.getFieldDisplayName() + ': ' + params.order.display; }, createFilter: createFilter, @@ -75,7 +75,7 @@ export default function TermsAggDefinition(Private) { makeOrderAgg: function (termsAgg, state) { state = state || {}; state.schema = orderAggSchema; - let orderAgg = new AggConfig(termsAgg.vis, state); + const orderAgg = new AggConfig(termsAgg.vis, state); orderAgg.id = termsAgg.id + '-orderAgg'; return orderAgg; }, @@ -88,18 +88,18 @@ export default function TermsAggDefinition(Private) { } }; - let INIT = {}; // flag to know when prevOrderBy has changed + const INIT = {}; // flag to know when prevOrderBy has changed let prevOrderBy = INIT; $scope.$watch('responseValueAggs', updateOrderAgg); $scope.$watch('agg.params.orderBy', updateOrderAgg); function updateOrderAgg() { - let agg = $scope.agg; - let aggs = agg.vis.aggs; - let params = agg.params; - let orderBy = params.orderBy; - let paramDef = agg.type.params.byName.orderAgg; + const agg = $scope.agg; + const aggs = agg.vis.aggs; + const params = agg.params; + const orderBy = params.orderBy; + const paramDef = agg.type.params.byName.orderAgg; // setup the initial value of orderBy if (!orderBy && prevOrderBy === INIT) { @@ -132,9 +132,9 @@ export default function TermsAggDefinition(Private) { } }, write: function (agg, output) { - let vis = agg.vis; - let dir = agg.params.order.val; - let order = output.params.order = {}; + const vis = agg.vis; + const dir = agg.params.order.val; + const order = output.params.order = {}; let orderAgg = agg.params.orderAgg || vis.aggs.getResponseAggById(agg.params.orderBy); @@ -158,7 +158,7 @@ export default function TermsAggDefinition(Private) { return; } - let orderAggId = orderAgg.id; + const orderAggId = orderAgg.id; if (orderAgg.parentId) { orderAgg = vis.aggs.byId[orderAgg.parentId]; } diff --git a/src/ui/public/agg_types/index.js b/src/ui/public/agg_types/index.js index 762a9dbab4a99..ad7af3709460e 100644 --- a/src/ui/public/agg_types/index.js +++ b/src/ui/public/agg_types/index.js @@ -21,7 +21,7 @@ import AggTypesBucketsSignificantTermsProvider from 'ui/agg_types/buckets/signif import AggTypesBucketsGeoHashProvider from 'ui/agg_types/buckets/geo_hash'; export default function AggTypeService(Private) { - let aggs = { + const aggs = { metrics: [ Private(AggTypesMetricsCountProvider), Private(AggTypesMetricsAvgProvider), diff --git a/src/ui/public/agg_types/metrics/avg.js b/src/ui/public/agg_types/metrics/avg.js index 4c7fc8ed50a1b..23851e3b887d7 100644 --- a/src/ui/public/agg_types/metrics/avg.js +++ b/src/ui/public/agg_types/metrics/avg.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricAvgProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'avg', diff --git a/src/ui/public/agg_types/metrics/cardinality.js b/src/ui/public/agg_types/metrics/cardinality.js index 76fed873e87e5..8d9b81abd6a60 100644 --- a/src/ui/public/agg_types/metrics/cardinality.js +++ b/src/ui/public/agg_types/metrics/cardinality.js @@ -2,8 +2,8 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_ag import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function AggTypeMetricCardinalityProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); return new MetricAggType({ name: 'cardinality', diff --git a/src/ui/public/agg_types/metrics/count.js b/src/ui/public/agg_types/metrics/count.js index fcad3d8dffa06..2e76b8fc5c2d3 100644 --- a/src/ui/public/agg_types/metrics/count.js +++ b/src/ui/public/agg_types/metrics/count.js @@ -2,8 +2,8 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_ag import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function AggTypeMetricCountProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); return new MetricAggType({ name: 'count', diff --git a/src/ui/public/agg_types/metrics/get_response_agg_config_class.js b/src/ui/public/agg_types/metrics/get_response_agg_config_class.js index b9112f343e81b..07a54b2366b64 100644 --- a/src/ui/public/agg_types/metrics/get_response_agg_config_class.js +++ b/src/ui/public/agg_types/metrics/get_response_agg_config_class.js @@ -30,7 +30,7 @@ export default function ResponseAggConfigProvider() { this.key = key; this.parentId = this.id; - let subId = String(key); + const subId = String(key); if (subId.indexOf('.') > -1) { this.id = this.parentId + '[\'' + subId.replace(/'/g, '\\\'') + '\']'; } else { diff --git a/src/ui/public/agg_types/metrics/max.js b/src/ui/public/agg_types/metrics/max.js index 2e39117904bc3..240baa5da3f20 100644 --- a/src/ui/public/agg_types/metrics/max.js +++ b/src/ui/public/agg_types/metrics/max.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricMaxProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'max', diff --git a/src/ui/public/agg_types/metrics/median.js b/src/ui/public/agg_types/metrics/median.js index 0b01fbbd1b116..498d2deb0bc60 100644 --- a/src/ui/public/agg_types/metrics/median.js +++ b/src/ui/public/agg_types/metrics/median.js @@ -3,9 +3,9 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_ag import AggTypesMetricsGetResponseAggConfigClassProvider from 'ui/agg_types/metrics/get_response_agg_config_class'; import AggTypesMetricsPercentilesProvider from 'ui/agg_types/metrics/percentiles'; export default function AggTypeMetricMedianProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let percentiles = Private(AggTypesMetricsPercentilesProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const percentiles = Private(AggTypesMetricsPercentilesProvider); return new MetricAggType({ name: 'median', diff --git a/src/ui/public/agg_types/metrics/metric_agg_type.js b/src/ui/public/agg_types/metrics/metric_agg_type.js index 445da4549868c..227a10b08ff7c 100644 --- a/src/ui/public/agg_types/metrics/metric_agg_type.js +++ b/src/ui/public/agg_types/metrics/metric_agg_type.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import AggTypesAggTypeProvider from 'ui/agg_types/agg_type'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function MetricAggTypeProvider(Private) { - let AggType = Private(AggTypesAggTypeProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const AggType = Private(AggTypesAggTypeProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); _.class(MetricAggType).inherits(AggType); function MetricAggType(config) { @@ -24,7 +24,7 @@ export default function MetricAggTypeProvider(Private) { */ MetricAggType.prototype.getValue = function (agg, bucket) { // Metric types where an empty set equals `zero` - let isSettableToZero = ['cardinality', 'sum'].indexOf(agg.__type.name) !== -1; + const isSettableToZero = ['cardinality', 'sum'].indexOf(agg.__type.name) !== -1; // Return proper values when no buckets are present // `Count` handles empty sets properly @@ -42,7 +42,7 @@ export default function MetricAggTypeProvider(Private) { * @return {FieldFromat} */ MetricAggType.prototype.getFormat = function (agg) { - let field = agg.getField(); + const field = agg.getField(); return field ? field.format : fieldFormats.getDefaultInstance('number'); }; diff --git a/src/ui/public/agg_types/metrics/min.js b/src/ui/public/agg_types/metrics/min.js index d60b04f959f8d..f0ba6ea05d3c5 100644 --- a/src/ui/public/agg_types/metrics/min.js +++ b/src/ui/public/agg_types/metrics/min.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricMinProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'min', diff --git a/src/ui/public/agg_types/metrics/percentile_ranks.js b/src/ui/public/agg_types/metrics/percentile_ranks.js index 87891eb9d9019..9771ae7d3a252 100644 --- a/src/ui/public/agg_types/metrics/percentile_ranks.js +++ b/src/ui/public/agg_types/metrics/percentile_ranks.js @@ -7,16 +7,16 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import getPercentileValue from './percentiles_get_value'; export default function AggTypeMetricPercentileRanksProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); // required by the values editor - let valueProps = { + const valueProps = { makeLabel: function () { - let field = this.getField(); - let format = (field && field.format) || fieldFormats.getDefaultInstance('number'); + const field = this.getField(); + const format = (field && field.format) || fieldFormats.getDefaultInstance('number'); const label = this.params.customLabel || this.getFieldDisplayName(); return 'Percentile rank ' + format.convert(this.key, 'text') + ' of "' + label + '"'; @@ -46,7 +46,7 @@ export default function AggTypeMetricPercentileRanksProvider(Private) { } ], getResponseAggs: function (agg) { - let ValueAggConfig = getResponseAggConfigClass(agg, valueProps); + const ValueAggConfig = getResponseAggConfigClass(agg, valueProps); return agg.params.values.map(function (value) { return new ValueAggConfig(value); diff --git a/src/ui/public/agg_types/metrics/percentiles.js b/src/ui/public/agg_types/metrics/percentiles.js index b1ef53fee93cc..e7da7bb599a50 100644 --- a/src/ui/public/agg_types/metrics/percentiles.js +++ b/src/ui/public/agg_types/metrics/percentiles.js @@ -8,13 +8,13 @@ import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import getPercentileValue from './percentiles_get_value'; export default function AggTypeMetricPercentilesProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); // required by the percentiles editor - let valueProps = { + const valueProps = { makeLabel: function () { const label = this.params.customLabel || this.getFieldDisplayName(); return ordinalSuffix(this.key) + ' percentile of ' + label; @@ -44,7 +44,7 @@ export default function AggTypeMetricPercentilesProvider(Private) { } ], getResponseAggs: function (agg) { - let ValueAggConfig = getResponseAggConfigClass(agg, valueProps); + const ValueAggConfig = getResponseAggConfigClass(agg, valueProps); return agg.params.percents.map(function (percent) { return new ValueAggConfig(percent); diff --git a/src/ui/public/agg_types/metrics/std_deviation.js b/src/ui/public/agg_types/metrics/std_deviation.js index fc101110d4b89..675cc8b032803 100644 --- a/src/ui/public/agg_types/metrics/std_deviation.js +++ b/src/ui/public/agg_types/metrics/std_deviation.js @@ -2,12 +2,12 @@ import _ from 'lodash'; import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; import AggTypesMetricsGetResponseAggConfigClassProvider from 'ui/agg_types/metrics/get_response_agg_config_class'; export default function AggTypeMetricStandardDeviationProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); - let getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const getResponseAggConfigClass = Private(AggTypesMetricsGetResponseAggConfigClassProvider); - let responseAggConfigProps = { + const responseAggConfigProps = { valProp: function () { - let details = this.keyedDetails(this.params.customLabel)[this.key]; + const details = this.keyedDetails(this.params.customLabel)[this.key]; return details.valProp; }, makeLabel: function () { @@ -45,7 +45,7 @@ export default function AggTypeMetricStandardDeviationProvider(Private) { ], getResponseAggs: function (agg) { - let ValueAggConfig = getResponseAggConfigClass(agg, responseAggConfigProps); + const ValueAggConfig = getResponseAggConfigClass(agg, responseAggConfigProps); return [ new ValueAggConfig('std_lower'), diff --git a/src/ui/public/agg_types/metrics/sum.js b/src/ui/public/agg_types/metrics/sum.js index b90309e917f9d..2893802678139 100644 --- a/src/ui/public/agg_types/metrics/sum.js +++ b/src/ui/public/agg_types/metrics/sum.js @@ -1,7 +1,7 @@ import AggTypesMetricsMetricAggTypeProvider from 'ui/agg_types/metrics/metric_agg_type'; export default function AggTypeMetricSumProvider(Private) { - let MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); + const MetricAggType = Private(AggTypesMetricsMetricAggTypeProvider); return new MetricAggType({ name: 'sum', diff --git a/src/ui/public/agg_types/param_types/field.js b/src/ui/public/agg_types/param_types/field.js index 611c6b545390a..7960fd98039e7 100644 --- a/src/ui/public/agg_types/param_types/field.js +++ b/src/ui/public/agg_types/param_types/field.js @@ -7,7 +7,7 @@ import IndexedArray from 'ui/indexed_array'; import Notifier from 'ui/notify/notifier'; export default function FieldAggParamFactory(Private, $filter) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); const notifier = new Notifier(); _.class(FieldAggParam).inherits(BaseAggParam); @@ -88,7 +88,7 @@ export default function FieldAggParamFactory(Private, $filter) { * @return {undefined} */ FieldAggParam.prototype.write = function (aggConfig, output) { - let field = aggConfig.getField(); + const field = aggConfig.getField(); if (!field) { throw new TypeError('"field" is a required parameter'); diff --git a/src/ui/public/agg_types/param_types/optioned.js b/src/ui/public/agg_types/param_types/optioned.js index 2e161a879a6c5..7fb0f06bf6c95 100644 --- a/src/ui/public/agg_types/param_types/optioned.js +++ b/src/ui/public/agg_types/param_types/optioned.js @@ -3,7 +3,7 @@ import IndexedArray from 'ui/indexed_array'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function OptionedAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(OptionedAggParam).inherits(BaseAggParam); function OptionedAggParam(config) { diff --git a/src/ui/public/agg_types/param_types/raw_json.js b/src/ui/public/agg_types/param_types/raw_json.js index 25f160174230d..b865b2312c896 100644 --- a/src/ui/public/agg_types/param_types/raw_json.js +++ b/src/ui/public/agg_types/param_types/raw_json.js @@ -3,7 +3,7 @@ import editorHtml from 'ui/agg_types/controls/raw_json.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function RawJSONAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(RawJSONAggParam).inherits(BaseAggParam); function RawJSONAggParam(config) { @@ -26,7 +26,7 @@ export default function RawJSONAggParamFactory(Private) { */ RawJSONAggParam.prototype.write = function (aggConfig, output) { let paramJSON; - let param = aggConfig.params[this.name]; + const param = aggConfig.params[this.name]; if (!param) { return; @@ -45,7 +45,7 @@ export default function RawJSONAggParamFactory(Private) { .keys() .union(_.keys(b)) .transform(function (dest, key) { - let val = compare(a[key], b[key]); + const val = compare(a[key], b[key]); if (val !== undefined) dest[key] = val; }, {}) .value(); diff --git a/src/ui/public/agg_types/param_types/regex.js b/src/ui/public/agg_types/param_types/regex.js index 3a38c06f8b9da..b00c6f654ea37 100644 --- a/src/ui/public/agg_types/param_types/regex.js +++ b/src/ui/public/agg_types/param_types/regex.js @@ -3,7 +3,7 @@ import editorHtml from 'ui/agg_types/controls/regular_expression.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function RegexAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(RegexAggParam).inherits(BaseAggParam); function RegexAggParam(config) { @@ -33,15 +33,15 @@ export default function RegexAggParamFactory(Private) { * @return {undefined} */ RegexAggParam.prototype.write = function (aggConfig, output) { - let param = aggConfig.params[this.name]; - let paramType = aggConfig.type.params.byName[this.name]; + const param = aggConfig.params[this.name]; + const paramType = aggConfig.type.params.byName[this.name]; // clear aggParam if pattern is not set or is disabled if (!param || !param.pattern || !param.pattern.length || paramType.disabled(aggConfig)) { return; } - let obj = { + const obj = { pattern: param.pattern }; diff --git a/src/ui/public/agg_types/param_types/string.js b/src/ui/public/agg_types/param_types/string.js index 58803171c44a4..dc15d9eefdbdb 100644 --- a/src/ui/public/agg_types/param_types/string.js +++ b/src/ui/public/agg_types/param_types/string.js @@ -3,7 +3,7 @@ import editorHtml from 'ui/agg_types/controls/string.html'; import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base'; export default function FieldAggParamFactory(Private) { - let BaseAggParam = Private(AggTypesParamTypesBaseProvider); + const BaseAggParam = Private(AggTypesParamTypesBaseProvider); _.class(ScriptAggParam).inherits(BaseAggParam); function ScriptAggParam(config) { diff --git a/src/ui/public/bind/__tests__/bind.js b/src/ui/public/bind/__tests__/bind.js index e7acb9b037080..ad00339c6a033 100644 --- a/src/ui/public/bind/__tests__/bind.js +++ b/src/ui/public/bind/__tests__/bind.js @@ -16,7 +16,7 @@ describe('$scope.$bind', function () { expect($rootScope.$bind).to.be.a('function'); expect($scope).to.have.property('$bind', $rootScope.$bind); - let $isoScope = $scope.$new(true); + const $isoScope = $scope.$new(true); expect($isoScope).to.have.property('$bind', $rootScope.$bind); }); @@ -33,7 +33,7 @@ describe('$scope.$bind', function () { }); it('sets up a binding from the child to the parent scope', function () { - let stub = sinon.stub(); + const stub = sinon.stub(); $rootScope.val = 'foo'; $scope.$bind('localVal', 'val'); @@ -47,8 +47,8 @@ describe('$scope.$bind', function () { }); it('pulls from the scopes $parent by default', function () { - let $parent = $rootScope.$new(); - let $self = $parent.$new(); + const $parent = $rootScope.$new(); + const $self = $parent.$new(); $parent.val = 'foo'; $self.val = 'bar'; @@ -58,8 +58,8 @@ describe('$scope.$bind', function () { }); it('accepts an alternate scope to read from', function () { - let $parent = $rootScope.$new(); - let $self = $parent.$new(); + const $parent = $rootScope.$new(); + const $self = $parent.$new(); $parent.val = 'foo'; $self.val = 'bar'; diff --git a/src/ui/public/bind/bind.js b/src/ui/public/bind/bind.js index ba16ddc5bfdcb..5d8afb8509d25 100644 --- a/src/ui/public/bind/bind.js +++ b/src/ui/public/bind/bind.js @@ -27,19 +27,19 @@ uiModules.get('kibana') * @return {undefined} */ $delegate.constructor.prototype.$bind = function (to, from, $sourceScope) { - let $source = $sourceScope || this.$parent; - let $target = this; + const $source = $sourceScope || this.$parent; + const $target = this; // parse expressions - let $to = $parse(to); + const $to = $parse(to); if (!$to.assign) errorNotAssignable(to, from); - let $from = $parse(from); + const $from = $parse(from); // bind scopes to expressions - let getTarget = function () { return $to($target); }; - let setTarget = function (v) { return $to.assign($target, v); }; - let getSource = function () { return $from($source); }; - let setSource = function (v) { return $from.assignOrFail($source, v); }; + const getTarget = function () { return $to($target); }; + const setTarget = function (v) { return $to.assign($target, v); }; + const getSource = function () { return $from($source); }; + const setSource = function (v) { return $from.assignOrFail($source, v); }; // to support writing from the child to the parent we need to know // which source has changed. Track the source value and anytime it @@ -55,19 +55,19 @@ uiModules.get('kibana') }; // if we are syncing down a literal, then we use loose equality check - let strict = !$from.literal; - let compare = strict ? strictEquality : angular.equals; + const strict = !$from.literal; + const compare = strict ? strictEquality : angular.equals; // push the initial value down, start off in sync setTarget(lastSourceVal); $target.$watch(function () { - let sourceVal = getSource(); - let targetVal = getTarget(); + const sourceVal = getSource(); + const targetVal = getTarget(); - let outOfSync = !compare(sourceVal, targetVal); - let sourceChanged = outOfSync && !compare(sourceVal, lastSourceVal); + const outOfSync = !compare(sourceVal, targetVal); + const sourceChanged = outOfSync && !compare(sourceVal, lastSourceVal); if (sourceChanged) setTarget(sourceVal); else if (outOfSync) setSource(targetVal); diff --git a/src/ui/public/binder/__tests__/binder.js b/src/ui/public/binder/__tests__/binder.js index 182050bb597fd..97d518a6008d9 100644 --- a/src/ui/public/binder/__tests__/binder.js +++ b/src/ui/public/binder/__tests__/binder.js @@ -16,13 +16,13 @@ describe('Binder class', function () { context('Constructing with a $scope', function () { it('accepts a $scope and listens for $destroy', function () { sinon.stub($scope, '$on'); - let binder = new Binder($scope); + const binder = new Binder($scope); expect($scope.$on.callCount).to.be(1); expect($scope.$on.args[0][0]).to.be('$destroy'); }); it('unbinds when the $scope is destroyed', function () { - let binder = new Binder($scope); + const binder = new Binder($scope); sinon.stub(binder, 'destroy'); $scope.$destroy(); expect(binder.destroy.callCount).to.be(1); @@ -31,12 +31,12 @@ describe('Binder class', function () { describe('Binder#on', function () { it('binds to normal event emitters', function () { - let binder = new Binder(); - let emitter = { + const binder = new Binder(); + const emitter = { on: sinon.stub(), removeListener: sinon.stub() }; - let handler = sinon.stub(); + const handler = sinon.stub(); binder.on(emitter, 'click', handler); expect(emitter.on.callCount).to.be(1); @@ -52,9 +52,9 @@ describe('Binder class', function () { describe('Binder#jqOn', function () { it('binds jquery event handlers', function () { - let binder = new Binder(); - let el = document.createElement('div'); - let handler = sinon.stub(); + const binder = new Binder(); + const el = document.createElement('div'); + const handler = sinon.stub(); binder.jqOn(el, 'click', handler); $(el).click(); diff --git a/src/ui/public/chrome/__tests__/nav_controls.js b/src/ui/public/chrome/__tests__/nav_controls.js index dda0bdc483465..921ee5e7710f9 100644 --- a/src/ui/public/chrome/__tests__/nav_controls.js +++ b/src/ui/public/chrome/__tests__/nav_controls.js @@ -36,7 +36,7 @@ describe('chrome nav controls', function () { }; }); - let $el = compile(); + const $el = compile(); expect($el.find('#testTemplateEl')).to.have.length(1); }); @@ -63,7 +63,7 @@ describe('chrome nav controls', function () { }; }); - let $el = compile(); + const $el = compile(); expect( $el.find('.testControl') .toArray() diff --git a/src/ui/public/chrome/api/angular.js b/src/ui/public/chrome/api/angular.js index 5755dafff9166..c1dbbd2045ea3 100644 --- a/src/ui/public/chrome/api/angular.js +++ b/src/ui/public/chrome/api/angular.js @@ -12,7 +12,7 @@ module.exports = function (chrome, internals) { chrome.getBreadcrumbs = _.noop; chrome.setupAngular = function () { - let kibana = modules.get('kibana'); + const kibana = modules.get('kibana'); _.forOwn(chrome.getInjected(), function (val, name) { kibana.value(name, val); @@ -27,7 +27,7 @@ module.exports = function (chrome, internals) { .value('sessionId', Date.now()) .value('chrome', chrome) .value('esUrl', (function () { - let a = document.createElement('a'); + const a = document.createElement('a'); a.href = chrome.addBasePath('/elasticsearch'); return a.href; }())) @@ -43,7 +43,7 @@ module.exports = function (chrome, internals) { }; chrome.getBreadcrumbs = () => { - let path = $location.path(); + const path = $location.path(); let length = path.length - 1; // trim trailing slash diff --git a/src/ui/public/chrome/api/nav.js b/src/ui/public/chrome/api/nav.js index f66db80a634e5..b592eaf0eb019 100644 --- a/src/ui/public/chrome/api/nav.js +++ b/src/ui/public/chrome/api/nav.js @@ -19,10 +19,10 @@ export default function (chrome, internals) { }; chrome.addBasePath = function (url) { - let isUrl = url && isString(url); + const isUrl = url && isString(url); if (!isUrl) return url; - let parsed = parse(url, true, true); + const parsed = parse(url, true, true); if (!parsed.host && parsed.pathname) { if (parsed.pathname[0] === '/') { parsed.pathname = chrome.getBasePath() + parsed.pathname; @@ -126,7 +126,7 @@ export default function (chrome, internals) { internals.nav.forEach(link => { // convert all link urls to absolute urls - let a = document.createElement('a'); + const a = document.createElement('a'); a.setAttribute('href', link.url); link.url = a.href; }); diff --git a/src/ui/public/chrome/api/theme.js b/src/ui/public/chrome/api/theme.js index 192239cd91488..f2fee099ad015 100644 --- a/src/ui/public/chrome/api/theme.js +++ b/src/ui/public/chrome/api/theme.js @@ -81,8 +81,8 @@ module.exports = function (chrome, internals) { * @return {chrome} */ chrome.removeApplicationClass = function (val) { - let classesToRemove = [].concat(val || []); - let classes = internals.applicationClasses || []; + const classesToRemove = [].concat(val || []); + const classes = internals.applicationClasses || []; _.pull(classes, ...classesToRemove); internals.applicationClasses = classes; diff --git a/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js b/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js index 3f0dac3370d89..19c8d7f62a732 100644 --- a/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js +++ b/src/ui/public/chrome/directives/global_nav/app_switcher/__tests__/app_switcher.js @@ -18,7 +18,7 @@ describe('appSwitcher directive', function () { function setup(href, links) { return ngMock.inject(function ($window, $rootScope, $compile, Private) { - let domLocation = Private(DomLocationProvider); + const domLocation = Private(DomLocationProvider); $rootScope.chrome = { getNavLinks: constant(cloneDeep(links)), @@ -46,14 +46,14 @@ describe('appSwitcher directive', function () { } context('when one link is for the active app', function () { - let myLink = { + const myLink = { active: true, title: 'myLink', url: 'http://localhost:555/app/myApp', lastSubUrl: 'http://localhost:555/app/myApp#/lastSubUrl' }; - let notMyLink = { + const notMyLink = { active: false, title: 'notMyLink', url: 'http://localhost:555/app/notMyApp', @@ -63,27 +63,27 @@ describe('appSwitcher directive', function () { beforeEach(setup('http://localhost:5555/app/myApp/', [myLink, notMyLink])); it('links to the inactive apps base url', function () { - let $myLink = env.$el.findTestSubject('appLink').eq(0); + const $myLink = env.$el.findTestSubject('appLink').eq(0); expect($myLink.prop('href')).to.be(myLink.url); expect($myLink.prop('href')).to.not.be(myLink.lastSubUrl); }); it('links to the inactive apps last sub url', function () { - let $notMyLink = env.$el.findTestSubject('appLink').eq(1); + const $notMyLink = env.$el.findTestSubject('appLink').eq(1); expect($notMyLink.prop('href')).to.be(notMyLink.lastSubUrl); expect($notMyLink.prop('href')).to.not.be(notMyLink.url); }); }); context('when none of the links are for the active app', function () { - let myLink = { + const myLink = { active: false, title: 'myLink', url: 'http://localhost:555/app/myApp', lastSubUrl: 'http://localhost:555/app/myApp#/lastSubUrl' }; - let notMyLink = { + const notMyLink = { active: false, title: 'notMyLink', url: 'http://localhost:555/app/notMyApp', @@ -93,9 +93,9 @@ describe('appSwitcher directive', function () { beforeEach(setup('http://localhost:5555/app/myApp/', [myLink, notMyLink])); it('links to the lastSubUrl for each', function () { - let $links = env.$el.findTestSubject('appLink'); - let $myLink = $links.eq(0); - let $notMyLink = $links.eq(1); + const $links = env.$el.findTestSubject('appLink'); + const $myLink = $links.eq(0); + const $notMyLink = $links.eq(1); expect($myLink.prop('href')).to.be(myLink.lastSubUrl); expect($myLink.prop('href')).to.not.be(myLink.url); @@ -106,19 +106,19 @@ describe('appSwitcher directive', function () { }); context('clicking a link with matching href but missing hash', function () { - let url = 'http://localhost:555/app/myApp?query=1'; + const url = 'http://localhost:555/app/myApp?query=1'; beforeEach(setup(url + '#/lastSubUrl', [ { url: url } ])); it('just prevents propogation (no reload)', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isDefaultPrevented()).to.be(false); expect(event.isPropagationStopped()).to.be(false); - let $link = env.$el.findTestSubject('appLink'); + const $link = env.$el.findTestSubject('appLink'); expect($link.prop('href')).to.be(url); $link.trigger(event); @@ -129,19 +129,19 @@ describe('appSwitcher directive', function () { }); context('clicking a link that matches entire url', function () { - let url = 'http://localhost:555/app/myApp#/lastSubUrl'; + const url = 'http://localhost:555/app/myApp#/lastSubUrl'; beforeEach(setup(url, [ { url: url } ])); it('calls window.location.reload and prevents propogation', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isDefaultPrevented()).to.be(false); expect(event.isPropagationStopped()).to.be(false); - let $link = env.$el.findTestSubject('appLink'); + const $link = env.$el.findTestSubject('appLink'); expect($link.prop('href')).to.be(env.currentHref); $link.trigger(event); @@ -152,21 +152,21 @@ describe('appSwitcher directive', function () { }); context('clicking a link with matching href but changed hash', function () { - let rootUrl = 'http://localhost:555/app/myApp?query=1'; - let url = rootUrl + '#/lastSubUrl2'; + const rootUrl = 'http://localhost:555/app/myApp?query=1'; + const url = rootUrl + '#/lastSubUrl2'; beforeEach(setup(url + '#/lastSubUrl', [ { url: url } ])); it('calls window.location.reload and prevents propogation', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isDefaultPrevented()).to.be(false); expect(event.isPropagationStopped()).to.be(false); - let $link = env.$el.findTestSubject('appLink'); + const $link = env.$el.findTestSubject('appLink'); expect($link.prop('href')).to.be(url); $link.trigger(event); @@ -185,7 +185,7 @@ describe('appSwitcher directive', function () { ])); it('allows click through', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isPropagationStopped()).to.be(false); @@ -206,7 +206,7 @@ describe('appSwitcher directive', function () { ])); it('allows click through', function () { - let event = new $.Event('click'); + const event = new $.Event('click'); expect(env.location.reload.callCount).to.be(0); expect(event.isPropagationStopped()).to.be(false); diff --git a/src/ui/public/collapsible_sidebar/collapsible_sidebar.js b/src/ui/public/collapsible_sidebar/collapsible_sidebar.js index d19a70af9643e..fb99712ac49f7 100644 --- a/src/ui/public/collapsible_sidebar/collapsible_sidebar.js +++ b/src/ui/public/collapsible_sidebar/collapsible_sidebar.js @@ -8,15 +8,15 @@ uiModules .get('kibana') .directive('collapsibleSidebar', function () { // simply a list of all of all of angulars .col-md-* classes except 12 - let listOfWidthClasses = _.times(11, function (i) { return 'col-md-' + i; }); + const listOfWidthClasses = _.times(11, function (i) { return 'col-md-' + i; }); return { restrict: 'C', link: function ($scope, $elem) { - let $collapser = $(''); - let $siblings = $elem.siblings(); + const $collapser = $(''); + const $siblings = $elem.siblings(); - let siblingsClass = listOfWidthClasses.reduce(function (prev, className) { + const siblingsClass = listOfWidthClasses.reduce(function (prev, className) { if (prev) return prev; return $siblings.hasClass(className) && className; }, false); diff --git a/src/ui/public/courier/_redirect_when_missing.js b/src/ui/public/courier/_redirect_when_missing.js index b86c75cba4129..5388cb65a879f 100644 --- a/src/ui/public/courier/_redirect_when_missing.js +++ b/src/ui/public/courier/_redirect_when_missing.js @@ -1,9 +1,9 @@ import errors from 'ui/errors'; export default function RedirectWhenMissingFn($location, kbnUrl, Notifier, Promise) { - let SavedObjectNotFound = errors.SavedObjectNotFound; + const SavedObjectNotFound = errors.SavedObjectNotFound; - let notify = new Notifier(); + const notify = new Notifier(); /** * Creates an error handler that will redirect to a url when a SavedObjectNotFound diff --git a/src/ui/public/courier/_request_queue.js b/src/ui/public/courier/_request_queue.js index b6dba26b187f1..b52a8a2fb4be3 100644 --- a/src/ui/public/courier/_request_queue.js +++ b/src/ui/public/courier/_request_queue.js @@ -6,7 +6,7 @@ export default function PendingRequestList() { * they are processed by fetch.[sourceType](). * @type {Array} */ - let queue = []; + const queue = []; queue.getInactive = function (/* strategies */) { return queue.get.apply(queue, arguments) diff --git a/src/ui/public/courier/courier.js b/src/ui/public/courier/courier.js index 4e09d24a8ef82..b489460f8501c 100644 --- a/src/ui/public/courier/courier.js +++ b/src/ui/public/courier/courier.js @@ -24,18 +24,18 @@ import RedirectWhenMissingProvider from './_redirect_when_missing'; uiModules.get('kibana/courier') .service('courier', function ($rootScope, Private, Promise, indexPatterns) { function Courier() { - let self = this; + const self = this; - let DocSource = Private(DocSourceProvider); - let SearchSource = Private(SearchSourceProvider); - let searchStrategy = Private(SearchStrategyProvider); + const DocSource = Private(DocSourceProvider); + const SearchSource = Private(SearchSourceProvider); + const searchStrategy = Private(SearchStrategyProvider); - let requestQueue = Private(RequestQueueProvider); - let errorHandlers = Private(ErrorHandlersProvider); + const requestQueue = Private(RequestQueueProvider); + const errorHandlers = Private(ErrorHandlersProvider); - let fetch = Private(FetchProvider); - let docLooper = self.docLooper = Private(DocLooperProvider); - let searchLooper = self.searchLooper = Private(SearchLooperProvider); + const fetch = Private(FetchProvider); + const docLooper = self.docLooper = Private(DocLooperProvider); + const searchLooper = self.searchLooper = Private(SearchLooperProvider); // expose some internal modules self.setRootSearchSource = Private(RootSearchSourceProvider).set; @@ -47,7 +47,7 @@ uiModules.get('kibana/courier') self.DocSource = DocSource; self.SearchSource = SearchSource; - let HastyRefresh = errors.HastyRefresh; + const HastyRefresh = errors.HastyRefresh; /** * update the time between automatic search requests @@ -135,8 +135,8 @@ uiModules.get('kibana/courier') // Listen for refreshInterval changes $rootScope.$watchCollection('timefilter.refreshInterval', function () { - let refreshValue = _.get($rootScope, 'timefilter.refreshInterval.value'); - let refreshPause = _.get($rootScope, 'timefilter.refreshInterval.pause'); + const refreshValue = _.get($rootScope, 'timefilter.refreshInterval.value'); + const refreshPause = _.get($rootScope, 'timefilter.refreshInterval.pause'); if (_.isNumber(refreshValue) && !refreshPause) { self.fetchInterval(refreshValue); } else { @@ -144,7 +144,7 @@ uiModules.get('kibana/courier') } }); - let onFatalDefer = Promise.defer(); + const onFatalDefer = Promise.defer(); onFatalDefer.promise.then(self.close); Notifier.fatalCallbacks.push(onFatalDefer.resolve); } diff --git a/src/ui/public/courier/data_source/__tests__/decorate_query.js b/src/ui/public/courier/data_source/__tests__/decorate_query.js index adae8151b2dcb..b72146bf8e38e 100644 --- a/src/ui/public/courier/data_source/__tests__/decorate_query.js +++ b/src/ui/public/courier/data_source/__tests__/decorate_query.js @@ -18,7 +18,7 @@ describe('Query decorator', function () { function ($provide) { // Super simple config stub $provide.service('config', function () { - let keys = {}; + const keys = {}; return { get: function (key) { return keys[key]; }, set: function (key, value) { keys[key] = value; } diff --git a/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js b/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js index 061e73e7adfe8..3ab6983a75254 100644 --- a/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js +++ b/src/ui/public/courier/data_source/__tests__/normalize_sort_request.js @@ -24,8 +24,8 @@ describe('SearchSource#normalizeSortRequest', function () { })); it('should return an array', function () { - let sortable = { someField: 'desc'}; - let result = normalizeSortRequest(sortable, indexPattern); + const sortable = { someField: 'desc'}; + const result = normalizeSortRequest(sortable, indexPattern); expect(result).to.be.an(Array); expect(result).to.eql(normalizedSort); // ensure object passed in is not mutated @@ -34,27 +34,27 @@ describe('SearchSource#normalizeSortRequest', function () { }); it('should make plain string sort into the more verbose format', function () { - let result = normalizeSortRequest([{ someField: 'desc'}], indexPattern); + const result = normalizeSortRequest([{ someField: 'desc'}], indexPattern); expect(result).to.eql(normalizedSort); }); it('should append default sort options', function () { - let sortState = [{ + const sortState = [{ someField: { order: 'desc', unmapped_type: 'boolean' } }]; - let result = normalizeSortRequest(sortState, indexPattern); + const result = normalizeSortRequest(sortState, indexPattern); expect(result).to.eql(normalizedSort); }); it('should enable script based sorting', function () { - let fieldName = 'script string'; - let direction = 'desc'; - let indexField = indexPattern.fields.byName[fieldName]; + const fieldName = 'script string'; + const direction = 'desc'; + const indexField = indexPattern.fields.byName[fieldName]; - let sortState = {}; + const sortState = {}; sortState[fieldName] = direction; normalizedSort = { _script: { @@ -76,31 +76,31 @@ describe('SearchSource#normalizeSortRequest', function () { }); it('should use script based sorting only on sortable types', function () { - let fieldName = 'script murmur3'; - let direction = 'asc'; - let indexField = indexPattern.fields.byName[fieldName]; + const fieldName = 'script murmur3'; + const direction = 'asc'; + const indexField = indexPattern.fields.byName[fieldName]; - let sortState = {}; + const sortState = {}; sortState[fieldName] = direction; normalizedSort = {}; normalizedSort[fieldName] = { order: direction, unmapped_type: 'boolean' }; - let result = normalizeSortRequest([sortState], indexPattern); + const result = normalizeSortRequest([sortState], indexPattern); expect(result).to.eql([normalizedSort]); }); it('should remove unmapped_type parameter from _score sorting', function () { - let sortable = { _score: 'desc'}; - let expected = [{ + const sortable = { _score: 'desc'}; + const expected = [{ _score: { order: 'desc' } }]; - let result = normalizeSortRequest(sortable, indexPattern); + const result = normalizeSortRequest(sortable, indexPattern); expect(_.isEqual(result, expected)).to.be.ok(); }); diff --git a/src/ui/public/courier/data_source/_abstract.js b/src/ui/public/courier/data_source/_abstract.js index 0b6832f876ebe..94ab75906e0a1 100644 --- a/src/ui/public/courier/data_source/_abstract.js +++ b/src/ui/public/courier/data_source/_abstract.js @@ -10,13 +10,13 @@ import DecorateQueryProvider from './_decorate_query'; import FieldWildcardProvider from '../../field_wildcard'; export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) { - let requestQueue = Private(RequestQueueProvider); - let errorHandlers = Private(ErrorHandlersProvider); - let courierFetch = Private(FetchProvider); - let { fieldWildcardFilter } = Private(FieldWildcardProvider); + const requestQueue = Private(RequestQueueProvider); + const errorHandlers = Private(ErrorHandlersProvider); + const courierFetch = Private(FetchProvider); + const { fieldWildcardFilter } = Private(FieldWildcardProvider); function SourceAbstract(initialState, strategy) { - let self = this; + const self = this; self._instanceid = _.uniqueId('data_source'); self._state = (function () { @@ -81,7 +81,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * string of the state value to set */ SourceAbstract.prototype.set = function (state, val) { - let self = this; + const self = this; if (typeof state === 'string') { // the getter and setter methods check for undefined explicitly @@ -127,7 +127,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @return {Promise} */ SourceAbstract.prototype.onResults = function (handler) { - let self = this; + const self = this; return new PromiseEmitter(function (resolve, reject) { const defer = Promise.defer(); @@ -151,7 +151,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @return {Promise} */ SourceAbstract.prototype.onError = function (handler) { - let self = this; + const self = this; return new PromiseEmitter(function (resolve, reject) { const defer = Promise.defer(); @@ -174,7 +174,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @async */ SourceAbstract.prototype.fetch = function () { - let self = this; + const self = this; let req = _.first(self._myStartableQueued()); if (!req) { @@ -234,13 +234,13 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @resolved {Object|null} - the flat state of the SourceAbstract */ SourceAbstract.prototype._flatten = function () { - let type = this._getType(); + const type = this._getType(); // the merged state of this dataSource and it's ancestors - let flatState = {}; + const flatState = {}; // function used to write each property from each state object in the chain to flat state - let root = this; + const root = this; // start the chain at this source let current = this; @@ -257,12 +257,12 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) }); } - let prom = root._mergeProp(flatState, value, key); + const prom = root._mergeProp(flatState, value, key); return Promise.is(prom) ? prom : null; })) .then(function () { // move to this sources parent - let parent = current.getParent(); + const parent = current.getParent(); // keep calling until we reach the top parent if (parent) { current = parent; @@ -273,7 +273,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) .then(function () { if (type === 'search') { // This is down here to prevent the circular dependency - let decorateQuery = Private(DecorateQueryProvider); + const decorateQuery = Private(DecorateQueryProvider); flatState.body = flatState.body || {}; @@ -285,7 +285,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) } if (flatState.body.size > 0) { - let computedFields = flatState.index.getComputedFields(); + const computedFields = flatState.index.getComputedFields(); flatState.body.stored_fields = computedFields.storedFields; flatState.body.script_fields = flatState.body.script_fields || {}; flatState.body.docvalue_fields = flatState.body.docvalue_fields || []; @@ -309,7 +309,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * through otherwise it will filter out * @returns {function} */ - let filterNegate = function (reverse) { + const filterNegate = function (reverse) { return function (filter) { if (_.isUndefined(filter.meta) || _.isUndefined(filter.meta.negate)) return !reverse; return filter.meta && filter.meta.negate === reverse; @@ -321,7 +321,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @param {Object} filter - The filter to translate * @return {Object} the query version of that filter */ - let translateToQuery = function (filter) { + const translateToQuery = function (filter) { if (!filter) return; if (filter.query) { @@ -336,7 +336,7 @@ export default function SourceAbstractFactory(Private, Promise, PromiseEmitter) * @param {object} filter The filter to clean * @returns {object} */ - let cleanFilter = function (filter) { + const cleanFilter = function (filter) { return _.omit(filter, ['meta']); }; diff --git a/src/ui/public/courier/data_source/_decorate_query.js b/src/ui/public/courier/data_source/_decorate_query.js index bb6fca29200b6..d0f009bf0a81c 100644 --- a/src/ui/public/courier/data_source/_decorate_query.js +++ b/src/ui/public/courier/data_source/_decorate_query.js @@ -7,7 +7,7 @@ export default function DecorateQuery(config) { * @returns {object} */ return function (query) { - let queryOptions = config.get('query:queryString:options'); + const queryOptions = config.get('query:queryString:options'); if (_.has(query, 'query_string.query')) { _.extend(query.query_string, queryOptions); diff --git a/src/ui/public/courier/data_source/_doc_send_to_es.js b/src/ui/public/courier/data_source/_doc_send_to_es.js index f7191b03100a9..6f42abc54cfd8 100644 --- a/src/ui/public/courier/data_source/_doc_send_to_es.js +++ b/src/ui/public/courier/data_source/_doc_send_to_es.js @@ -12,8 +12,8 @@ import RequestQueueProvider from 'ui/courier/_request_queue'; import FetchProvider from 'ui/courier/fetch/fetch'; export default function (Promise, Private, es) { - let requestQueue = Private(RequestQueueProvider); - let courierFetch = Private(FetchProvider); + const requestQueue = Private(RequestQueueProvider); + const courierFetch = Private(FetchProvider); /** * Backend for doUpdate and doIndex @@ -23,9 +23,9 @@ export default function (Promise, Private, es) { * @param {String} body - HTTP request body */ return function (method, validateVersion, body, ignore) { - let doc = this; + const doc = this; // straight assignment will causes undefined values - let params = _.pick(this._state, ['id', 'type', 'index']); + const params = _.pick(this._state, ['id', 'type', 'index']); params.body = body; params.ignore = ignore || [409]; @@ -58,13 +58,13 @@ export default function (Promise, Private, es) { // notify pending request for this same document that we have updates docFetchProm.then(function (fetchResp) { // use the key to compair sources - let key = doc._versionKey(); + const key = doc._versionKey(); // clear the queue and filter out the removed items, pushing the // unmatched ones back in. - let respondTo = requestQueue.splice(0).filter(function (req) { - let isDoc = req.source._getType() === 'doc'; - let keyMatches = isDoc && req.source._versionKey() === key; + const respondTo = requestQueue.splice(0).filter(function (req) { + const isDoc = req.source._getType() === 'doc'; + const keyMatches = isDoc && req.source._versionKey() === key; // put some request back into the queue if (!keyMatches) { diff --git a/src/ui/public/courier/data_source/_normalize_sort_request.js b/src/ui/public/courier/data_source/_normalize_sort_request.js index 7bab633bf1d4c..57465b67618d3 100644 --- a/src/ui/public/courier/data_source/_normalize_sort_request.js +++ b/src/ui/public/courier/data_source/_normalize_sort_request.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function normalizeSortRequest(config) { - let defaultSortOptions = config.get('sort:options'); + const defaultSortOptions = config.get('sort:options'); /** * Decorate queries with default parameters @@ -9,7 +9,7 @@ export default function normalizeSortRequest(config) { * @returns {object} */ return function (sortObject, indexPattern) { - let normalizedSort = []; + const normalizedSort = []; // [].concat({}) -> [{}], [].concat([{}]) -> [{}] return [].concat(sortObject).map(function (sortable) { @@ -22,10 +22,10 @@ export default function normalizeSortRequest(config) { { someField: "desc" } into { someField: { "order": "desc"}} */ function normalize(sortable, indexPattern) { - let normalized = {}; + const normalized = {}; let sortField = _.keys(sortable)[0]; let sortValue = sortable[sortField]; - let indexField = indexPattern.fields.byName[sortField]; + const indexField = indexPattern.fields.byName[sortField]; if (indexField && indexField.scripted && indexField.sortable) { let direction; diff --git a/src/ui/public/courier/data_source/_root_search_source.js b/src/ui/public/courier/data_source/_root_search_source.js index c3cb53ffb33c1..634360220326e 100644 --- a/src/ui/public/courier/data_source/_root_search_source.js +++ b/src/ui/public/courier/data_source/_root_search_source.js @@ -1,11 +1,11 @@ import SearchSourceProvider from 'ui/courier/data_source/search_source'; export default function RootSearchSource(Private, $rootScope, timefilter, Notifier) { - let SearchSource = Private(SearchSourceProvider); + const SearchSource = Private(SearchSourceProvider); - let notify = new Notifier({ location: 'Root Search Source' }); + const notify = new Notifier({ location: 'Root Search Source' }); - let globalSource = new SearchSource(); + const globalSource = new SearchSource(); globalSource.inherits(false); // this is the final source, it has no parents globalSource.filter(function (globalSource) { // dynamic time filter will be called in the _flatten phase of things diff --git a/src/ui/public/courier/data_source/doc_source.js b/src/ui/public/courier/data_source/doc_source.js index 80be1cf7b6095..88742af068aff 100644 --- a/src/ui/public/courier/data_source/doc_source.js +++ b/src/ui/public/courier/data_source/doc_source.js @@ -19,10 +19,10 @@ import DocRequestProvider from '../fetch/request/doc'; import DocStrategyProvider from '../fetch/strategy/doc'; export default function DocSourceFactory(Private, Promise, es, sessionStorage) { - let sendToEs = Private(DocSendToEsProvider); - let SourceAbstract = Private(AbstractDataSourceProvider); - let DocRequest = Private(DocRequestProvider); - let docStrategy = Private(DocStrategyProvider); + const sendToEs = Private(DocSendToEsProvider); + const SourceAbstract = Private(AbstractDataSourceProvider); + const DocRequest = Private(DocRequestProvider); + const docStrategy = Private(DocStrategyProvider); _.class(DocSource).inherits(SourceAbstract); function DocSource(initialState) { @@ -109,7 +109,7 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { * @return {string} */ DocSource.prototype._versionKey = function () { - let state = this._state; + const state = this._state; if (!state.index || !state.type || !state.id) return; return 'DocVersion:' + ( @@ -135,10 +135,10 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { * @return {[type]} [description] */ DocSource.prototype._getStoredVersion = function () { - let key = this._versionKey(); + const key = this._versionKey(); if (!key) return; - let v = sessionStorage.get(key); + const v = sessionStorage.get(key); this._version = v ? _.parseInt(v) : void 0; return this._version; }; @@ -151,7 +151,7 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { DocSource.prototype._storeVersion = function (version) { if (!version) return this._clearVersion(); - let key = this._versionKey(); + const key = this._versionKey(); if (!key) return; this._version = version; sessionStorage.set(key, version); @@ -161,7 +161,7 @@ export default function DocSourceFactory(Private, Promise, es, sessionStorage) { * Clears the stored version for a DocSource */ DocSource.prototype._clearVersion = function () { - let key = this._versionKey(); + const key = this._versionKey(); if (!key) return; sessionStorage.remove(key); }; diff --git a/src/ui/public/courier/data_source/search_source.js b/src/ui/public/courier/data_source/search_source.js index f4279aee4940d..88ad242396f3d 100644 --- a/src/ui/public/courier/data_source/search_source.js +++ b/src/ui/public/courier/data_source/search_source.js @@ -60,13 +60,13 @@ import SegmentedRequestProvider from '../fetch/request/segmented'; import SearchStrategyProvider from '../fetch/strategy/search'; export default function SearchSourceFactory(Promise, Private, config) { - let SourceAbstract = Private(AbstractDataSourceProvider); - let SearchRequest = Private(SearchRequestProvider); - let SegmentedRequest = Private(SegmentedRequestProvider); - let searchStrategy = Private(SearchStrategyProvider); - let normalizeSortRequest = Private(NormalizeSortRequestProvider); + const SourceAbstract = Private(AbstractDataSourceProvider); + const SearchRequest = Private(SearchRequestProvider); + const SegmentedRequest = Private(SegmentedRequestProvider); + const searchStrategy = Private(SearchStrategyProvider); + const normalizeSortRequest = Private(NormalizeSortRequestProvider); - let forIp = Symbol('for which index pattern?'); + const forIp = Symbol('for which index pattern?'); function isIndexPattern(val) { return Boolean(val && typeof val.toIndexList === 'function'); @@ -100,11 +100,11 @@ export default function SearchSourceFactory(Promise, Private, config) { ]; SearchSource.prototype.index = function (indexPattern) { - let state = this._state; + const state = this._state; - let hasSource = state.source; - let sourceCameFromIp = hasSource && state.source.hasOwnProperty(forIp); - let sourceIsForOurIp = sourceCameFromIp && state.source[forIp] === state.index; + const hasSource = state.source; + const sourceCameFromIp = hasSource && state.source.hasOwnProperty(forIp); + const sourceIsForOurIp = sourceCameFromIp && state.source[forIp] === state.index; if (sourceIsForOurIp) { delete state.source; } @@ -147,7 +147,7 @@ export default function SearchSourceFactory(Promise, Private, config) { * @return {undefined|searchSource} */ SearchSource.prototype.getParent = function (onlyHardLinked) { - let self = this; + const self = this; if (self._parent === false) return; if (self._parent) return self._parent; return onlyHardLinked ? undefined : Private(rootSearchSource).get(); @@ -168,9 +168,9 @@ export default function SearchSourceFactory(Promise, Private, config) { }; SearchSource.prototype.onBeginSegmentedFetch = function (initFunction) { - let self = this; + const self = this; return Promise.try(function addRequest() { - let req = new SegmentedRequest(self, Promise.defer(), initFunction); + const req = new SegmentedRequest(self, Promise.defer(), initFunction); // return promises created by the completion handler so that // errors will bubble properly @@ -215,7 +215,7 @@ export default function SearchSourceFactory(Promise, Private, config) { */ SearchSource.prototype._mergeProp = function (state, val, key) { if (typeof val === 'function') { - let source = this; + const source = this; return Promise.cast(val(this)) .then(function (newVal) { return source._mergeProp(state, newVal, key); diff --git a/src/ui/public/courier/looper/_looper.js b/src/ui/public/courier/looper/_looper.js index 8ebf2df44d497..acb769c5f216b 100644 --- a/src/ui/public/courier/looper/_looper.js +++ b/src/ui/public/courier/looper/_looper.js @@ -4,7 +4,7 @@ import 'ui/promises'; import Notifier from 'ui/notify/notifier'; export default function LooperFactory($timeout, Promise) { - let notify = new Notifier(); + const notify = new Notifier(); function Looper(ms, fn) { this._fn = fn; @@ -130,7 +130,7 @@ export default function LooperFactory($timeout, Promise) { * @return {undefined} */ Looper.prototype._loopTheLoop = function () { - let self = this; + const self = this; if (self.active) { self.onHastyLoop(); diff --git a/src/ui/public/courier/looper/doc.js b/src/ui/public/courier/looper/doc.js index e0f21394777c8..1e5363897c513 100644 --- a/src/ui/public/courier/looper/doc.js +++ b/src/ui/public/courier/looper/doc.js @@ -3,15 +3,15 @@ import LooperProvider from './_looper'; import DocStrategyProvider from '../fetch/strategy/doc'; export default function DocLooperService(Private) { - let fetch = Private(FetchProvider); - let Looper = Private(LooperProvider); - let DocStrategy = Private(DocStrategyProvider); + const fetch = Private(FetchProvider); + const Looper = Private(LooperProvider); + const DocStrategy = Private(DocStrategyProvider); /** * The Looper which will manage the doc fetch interval * @type {Looper} */ - let docLooper = new Looper(1500, function () { + const docLooper = new Looper(1500, function () { fetch.fetchQueued(DocStrategy); }); diff --git a/src/ui/public/courier/looper/search.js b/src/ui/public/courier/looper/search.js index ae6867f77d50d..8cd4c895a2972 100644 --- a/src/ui/public/courier/looper/search.js +++ b/src/ui/public/courier/looper/search.js @@ -4,18 +4,18 @@ import RequestQueueProvider from '../_request_queue'; import LooperProvider from './_looper'; export default function SearchLooperService(Private, Promise, Notifier, $rootScope) { - let fetch = Private(FetchProvider); - let searchStrategy = Private(SearchStrategyProvider); - let requestQueue = Private(RequestQueueProvider); + const fetch = Private(FetchProvider); + const searchStrategy = Private(SearchStrategyProvider); + const requestQueue = Private(RequestQueueProvider); - let Looper = Private(LooperProvider); - let notif = new Notifier({ location: 'Search Looper' }); + const Looper = Private(LooperProvider); + const notif = new Notifier({ location: 'Search Looper' }); /** * The Looper which will manage the doc fetch interval * @type {Looper} */ - let searchLooper = new Looper(null, function () { + const searchLooper = new Looper(null, function () { $rootScope.$broadcast('courier:searchRefresh'); return fetch.these( requestQueue.getInactive(searchStrategy) diff --git a/src/ui/public/courier/saved_object/saved_object.js b/src/ui/public/courier/saved_object/saved_object.js index 8cfe0fe1bb39f..82c74fe83c8af 100644 --- a/src/ui/public/courier/saved_object/saved_object.js +++ b/src/ui/public/courier/saved_object/saved_object.js @@ -21,38 +21,38 @@ import SearchSourceProvider from '../data_source/search_source'; export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notifier, safeConfirm, indexPatterns) { - let DocSource = Private(DocSourceProvider); - let SearchSource = Private(SearchSourceProvider); - let mappingSetup = Private(MappingSetupProvider); + const DocSource = Private(DocSourceProvider); + const SearchSource = Private(SearchSourceProvider); + const mappingSetup = Private(MappingSetupProvider); function SavedObject(config) { if (!_.isObject(config)) config = {}; // save an easy reference to this - let self = this; + const self = this; /************ * Initialize config vars ************/ // the doc which is used to store this object - let docSource = new DocSource(); + const docSource = new DocSource(); // type name for this object, used as the ES-type - let type = config.type; + const type = config.type; // Create a notifier for sending alerts - let notify = new Notifier({ + const notify = new Notifier({ location: 'Saved ' + type }); // mapping definition for the fields that this object will expose - let mapping = mappingSetup.expandShorthand(config.mapping); + const mapping = mappingSetup.expandShorthand(config.mapping); // default field values, assigned when the source is loaded - let defaults = config.defaults || {}; + const defaults = config.defaults || {}; - let afterESResp = config.afterESResp || _.noop; - let customInit = config.init || _.noop; + const afterESResp = config.afterESResp || _.noop; + const customInit = config.init || _.noop; // optional search source which this object configures self.searchSource = config.searchSource && new SearchSource(); @@ -124,7 +124,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif if (resp.found != null && !resp.found) throw new errors.SavedObjectNotFound(type, self.id); - let meta = resp._source.kibanaSavedObjectMeta || {}; + const meta = resp._source.kibanaSavedObjectMeta || {}; delete resp._source.kibanaSavedObjectMeta; if (!config.indexPattern && self._source.indexPattern) { @@ -169,8 +169,8 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif state = {}; } - let oldState = self.searchSource.toJSON(); - let fnProps = _.transform(oldState, function (dynamic, val, name) { + const oldState = self.searchSource.toJSON(); + const fnProps = _.transform(oldState, function (dynamic, val, name) { if (_.isFunction(val)) dynamic[name] = val; }, {}); @@ -211,7 +211,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif * @return {Object} */ self.serialize = function () { - let body = {}; + const body = {}; _.forOwn(mapping, function (fieldMapping, fieldName) { if (self[fieldName] != null) { @@ -238,7 +238,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif */ self.save = function () { - let body = self.serialize(); + const body = self.serialize(); // Slugify the object id self.id = slugifyId(self.id); @@ -251,7 +251,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif }; self.saveSource = function (source) { - let finish = function (id) { + const finish = function (id) { self.id = id; return es.indices.refresh({ index: kbnIndex @@ -266,7 +266,7 @@ export default function SavedObjectFactory(es, kbnIndex, Promise, Private, Notif .catch(function (err) { // record exists, confirm overwriting if (_.get(err, 'origError.status') === 409) { - let confirmMessage = 'Are you sure you want to overwrite ' + self.title + '?'; + const confirmMessage = 'Are you sure you want to overwrite ' + self.title + '?'; return safeConfirm(confirmMessage).then( function () { diff --git a/src/ui/public/debounce/__tests__/debounce.js b/src/ui/public/debounce/__tests__/debounce.js index 5208365c38a8f..9169c76a93568 100644 --- a/src/ui/public/debounce/__tests__/debounce.js +++ b/src/ui/public/debounce/__tests__/debounce.js @@ -27,14 +27,14 @@ describe('debounce service', function () { describe('API', function () { it('should have a cancel method', function () { - let bouncer = debounce(function () {}, 100); + const bouncer = debounce(function () {}, 100); expect(bouncer).to.have.property('cancel'); }); }); describe('delayed execution', function () { it('should delay execution', function () { - let bouncer = debounce(spy, 100); + const bouncer = debounce(spy, 100); bouncer(); expect(spy.callCount).to.be(0); $timeout.flush(); @@ -42,7 +42,7 @@ describe('debounce service', function () { }); it('should fire on leading edge', function () { - let bouncer = debounce(spy, 100, { leading: true }); + const bouncer = debounce(spy, 100, { leading: true }); bouncer(); expect(spy.callCount).to.be(1); $timeout.flush(); @@ -50,7 +50,7 @@ describe('debounce service', function () { }); it('should only fire on leading edge', function () { - let bouncer = debounce(spy, 100, { leading: true, trailing: false }); + const bouncer = debounce(spy, 100, { leading: true, trailing: false }); bouncer(); expect(spy.callCount).to.be(1); $timeout.flush(); @@ -58,8 +58,8 @@ describe('debounce service', function () { }); it('should reset delayed execution', function (done) { - let cancelSpy = sinon.spy($timeout, 'cancel'); - let bouncer = debounce(spy, 100); + const cancelSpy = sinon.spy($timeout, 'cancel'); + const bouncer = debounce(spy, 100); bouncer(); setTimeout(function () { bouncer(); @@ -74,8 +74,8 @@ describe('debounce service', function () { describe('cancel', function () { it('should cancel the $timeout', function () { - let cancelSpy = sinon.spy($timeout, 'cancel'); - let bouncer = debounce(spy, 100); + const cancelSpy = sinon.spy($timeout, 'cancel'); + const bouncer = debounce(spy, 100); bouncer(); bouncer.cancel(); expect(cancelSpy.callCount).to.be(1); diff --git a/src/ui/public/debounce/debounce.js b/src/ui/public/debounce/debounce.js index 7f8652f39d8f5..fc541e108c25e 100644 --- a/src/ui/public/debounce/debounce.js +++ b/src/ui/public/debounce/debounce.js @@ -3,7 +3,7 @@ import uiModules from 'ui/modules'; // Debounce service, angularized version of lodash debounce // borrowed heavily from https://github.com/shahata/angular-debounce -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.service('debounce', ['$timeout', function ($timeout) { return function (func, wait, options) { @@ -20,14 +20,14 @@ module.service('debounce', ['$timeout', function ($timeout) { self = this; args = arguments; - let later = function () { + const later = function () { timeout = null; if (!options.leading || options.trailing) { result = func.apply(self, args); } }; - let callNow = options.leading && !timeout; + const callNow = options.leading && !timeout; if (timeout) { $timeout.cancel(timeout); diff --git a/src/ui/public/directives/__tests__/auto_select_if_only_one.js b/src/ui/public/directives/__tests__/auto_select_if_only_one.js index b414843698b9d..df5103f8d8a28 100644 --- a/src/ui/public/directives/__tests__/auto_select_if_only_one.js +++ b/src/ui/public/directives/__tests__/auto_select_if_only_one.js @@ -7,16 +7,16 @@ import 'ui/directives/auto_select_if_only_one'; describe('Auto-select if only one directive', function () { let $compile; let $rootScope; - let zeroOptions = []; - let oneOption = [{label: 'foo'}]; - let multiOptions = [{label: 'foo'}, {label: 'bar'}]; + const zeroOptions = []; + const oneOption = [{label: 'foo'}]; + const multiOptions = [{label: 'foo'}, {label: 'bar'}]; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; - let html = ''; + const html = ''; $compile(html)($rootScope); $rootScope.value = null; })); @@ -41,7 +41,7 @@ describe('Auto-select if only one directive', function () { it('should still auto select if the collection contains 2 items but is filtered to 1', function () { $rootScope.options = multiOptions; - let html = ''; $compile(html)($rootScope); $rootScope.value = null; diff --git a/src/ui/public/directives/__tests__/confirm-click.js b/src/ui/public/directives/__tests__/confirm-click.js index bdb7e7d62355e..8e0f2aefb3e3e 100644 --- a/src/ui/public/directives/__tests__/confirm-click.js +++ b/src/ui/public/directives/__tests__/confirm-click.js @@ -13,7 +13,7 @@ let $scope; let $elem; -let init = function (text) { +const init = function (text) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/directives/__tests__/css_truncate.js b/src/ui/public/directives/__tests__/css_truncate.js index 535200bb0abc6..f8a008f13049f 100644 --- a/src/ui/public/directives/__tests__/css_truncate.js +++ b/src/ui/public/directives/__tests__/css_truncate.js @@ -10,7 +10,7 @@ let $scope; let $elem; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/directives/__tests__/fixed_scroll.js b/src/ui/public/directives/__tests__/fixed_scroll.js index 7bcf4467ab740..b6488caf58a69 100644 --- a/src/ui/public/directives/__tests__/fixed_scroll.js +++ b/src/ui/public/directives/__tests__/fixed_scroll.js @@ -9,7 +9,7 @@ import Promise from 'bluebird'; describe('FixedScroll directive', function () { let compile; - let trash = []; + const trash = []; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function ($compile, $rootScope) { @@ -19,7 +19,7 @@ describe('FixedScroll directive', function () { // since the directive works at the sibling level we create a // parent for everything to happen in - let $parent = $('
').css({ + const $parent = $('
').css({ position: 'fixed', top: 0, left: 0, @@ -30,12 +30,12 @@ describe('FixedScroll directive', function () { $parent.appendTo(document.body); trash.push($parent); - let $el = $('
').css({ + const $el = $('
').css({ 'overflow-x': 'auto', 'width': $parent.width() }).appendTo($parent); - let $content = $('
').css({ + const $content = $('
').css({ width: $parent.width() * ratioX, height: $parent.height() * ratioY }).appendTo($el); @@ -67,26 +67,26 @@ describe('FixedScroll directive', function () { }); it('attaches a scroller below the element when the content is larger then the container', function () { - let els = compile(1.5); + const els = compile(1.5); expect(els.$scroller).to.have.length(1); }); it('copies the width of the container', function () { - let els = compile(1.5); + const els = compile(1.5); expect(els.$scroller.width()).to.be(els.$container.width()); }); it('mimics the scrollWidth of the element', function () { - let els = compile(1.5); + const els = compile(1.5); expect(els.$scroller.prop('scrollWidth')).to.be(els.$container.prop('scrollWidth')); }); describe('scroll event handling / tug of war prevention', function () { it('listens when needed, unlistens when not needed', function () { - let on = sinon.spy($.fn, 'on'); - let off = sinon.spy($.fn, 'off'); + const on = sinon.spy($.fn, 'on'); + const off = sinon.spy($.fn, 'off'); - let els = compile(1.5); + const els = compile(1.5); expect(on.callCount).to.be(2); checkThisVals('$.fn.on', on); @@ -130,12 +130,12 @@ describe('FixedScroll directive', function () { expect(spy.callCount).to.be(2); // first call should read the scrollLeft from the $container - let firstCall = spy.getCall(0); + const firstCall = spy.getCall(0); expect(firstCall.thisValue.is($from)).to.be(true); expect(firstCall.args).to.eql([]); // second call should be setting the scrollLeft on the $scroller - let secondCall = spy.getCall(1); + const secondCall = spy.getCall(1); expect(secondCall.thisValue.is($to)).to.be(true); expect(secondCall.args).to.eql([firstCall.returnValue]); }); diff --git a/src/ui/public/directives/__tests__/input_focus.js b/src/ui/public/directives/__tests__/input_focus.js index 5d30dbb52f0aa..e6d93ecef387e 100644 --- a/src/ui/public/directives/__tests__/input_focus.js +++ b/src/ui/public/directives/__tests__/input_focus.js @@ -12,7 +12,7 @@ describe('Input focus directive', function () { let $el; let selectedEl; let selectedText; - let inputValue = 'Input Text Value'; + const inputValue = 'Input Text Value'; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (_$compile_, _$rootScope_, _$timeout_) { diff --git a/src/ui/public/directives/__tests__/input_number.js b/src/ui/public/directives/__tests__/input_number.js index 6592ab76174a0..92b37e7b63a2f 100644 --- a/src/ui/public/directives/__tests__/input_number.js +++ b/src/ui/public/directives/__tests__/input_number.js @@ -6,7 +6,7 @@ import 'ui/directives/input_number'; describe('Number input directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -16,7 +16,7 @@ describe('Number input directive', function () { })); it('should allow whole numbers', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '123'; $rootScope.$digest(); @@ -32,7 +32,7 @@ describe('Number input directive', function () { }); it('should allow numbers with decimals', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '123.0'; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/json_input.js b/src/ui/public/directives/__tests__/json_input.js index b82de486c974c..9ee9cee7df1ad 100644 --- a/src/ui/public/directives/__tests__/json_input.js +++ b/src/ui/public/directives/__tests__/json_input.js @@ -7,7 +7,7 @@ import 'ui/directives/json_input'; describe('JSON input validation', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; let element; beforeEach(ngMock.module('kibana')); @@ -28,8 +28,8 @@ describe('JSON input validation', function () { }); it('should be able to not require keys', function () { - let html = ''; - let element = $compile(html)($rootScope); + const html = ''; + const element = $compile(html)($rootScope); element.val('{}'); element.trigger('input'); diff --git a/src/ui/public/directives/__tests__/paginated_selectable_list.js b/src/ui/public/directives/__tests__/paginated_selectable_list.js index a066d470b4497..30c5f906a5e37 100644 --- a/src/ui/public/directives/__tests__/paginated_selectable_list.js +++ b/src/ui/public/directives/__tests__/paginated_selectable_list.js @@ -3,7 +3,7 @@ import expect from 'expect.js'; import ngMock from 'ng_mock'; import _ from 'lodash'; -let objectList = [ +const objectList = [ { title: 'apple' }, { title: 'orange' }, { title: 'coconut' }, @@ -11,7 +11,7 @@ let objectList = [ { title: 'grapes' } ]; -let stringList = [ +const stringList = [ 'apple', 'orange', 'coconut', @@ -19,18 +19,18 @@ let stringList = [ 'grapes' ]; -let lists = [objectList, stringList, []]; +const lists = [objectList, stringList, []]; let $scope; let $element; let $isolatedScope; lists.forEach(function (list) { - let isArrayOfObjects = list.every((item) => { + const isArrayOfObjects = list.every((item) => { return _.isPlainObject(item); }); - let init = function (arr, willFail) { + const init = function (arr, willFail) { // Load the application ngMock.module('kibana'); @@ -83,8 +83,8 @@ lists.forEach(function (list) { }); it('should initially sort an array of objects in ascending order', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); expect($isolatedScope.hits).to.be.an('array'); @@ -104,8 +104,8 @@ lists.forEach(function (list) { }); it('should sort an array of objects in ascending order', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); $isolatedScope.isAscending = false; $isolatedScope.sortHits(list); @@ -122,8 +122,8 @@ lists.forEach(function (list) { }); it('should sort an array of objects in descending order', function () { - let property = $isolatedScope.listProperty; - let reversedList = property ? _.sortBy(list, property).reverse() : _.sortBy(list).reverse(); + const property = $isolatedScope.listProperty; + const reversedList = property ? _.sortBy(list, property).reverse() : _.sortBy(list).reverse(); $isolatedScope.isAscending = true; $isolatedScope.sortHits(list); @@ -146,8 +146,8 @@ lists.forEach(function (list) { }); it('should return the result of the function its passed', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); $isolatedScope.hits.forEach(function (hit, index) { if (property) { @@ -165,8 +165,8 @@ lists.forEach(function (list) { }); it('should return the result of the function its passed', function () { - let property = $isolatedScope.listProperty; - let sortedList = property ? _.sortBy(list, property) : _.sortBy(list); + const property = $isolatedScope.listProperty; + const sortedList = property ? _.sortBy(list, property) : _.sortBy(list); $isolatedScope.userOnSelect = function (val) { return val; }; diff --git a/src/ui/public/directives/__tests__/parse_query.js b/src/ui/public/directives/__tests__/parse_query.js index 6115bbdc20f35..fb2bc7bd13625 100644 --- a/src/ui/public/directives/__tests__/parse_query.js +++ b/src/ui/public/directives/__tests__/parse_query.js @@ -15,13 +15,13 @@ let $elemScope; let $elem; let cycleIndex = 0; -let markup = ''; +const markup = ''; let fromUser; import toUser from 'ui/parse_query/lib/to_user'; import 'ui/parse_query'; import ParseQueryLibFromUserProvider from 'ui/parse_query/lib/from_user'; -let init = function () { +const init = function () { // Load the application ngMock.module('kibana'); @@ -41,7 +41,7 @@ let init = function () { }); }; -let compile = function () { +const compile = function () { $rootScope.mockModel = 'cycle' + cycleIndex++; $rootScope.mockQueryInput = undefined; diff --git a/src/ui/public/directives/__tests__/timepicker.js b/src/ui/public/directives/__tests__/timepicker.js index e9327a76ec079..f4b7a561cda59 100644 --- a/src/ui/public/directives/__tests__/timepicker.js +++ b/src/ui/public/directives/__tests__/timepicker.js @@ -17,10 +17,10 @@ let $parentScope; let $scope; let $elem; -let anchor = '2014-01-01T06:06:06.666Z'; +const anchor = '2014-01-01T06:06:06.666Z'; let clock; -let init = function () { +const init = function () { // Load the application ngMock.module('kibana'); @@ -34,7 +34,7 @@ let init = function () { $parentScope = $rootScope; // Add some parameters to it - let timefilter = { + const timefilter = { time : { from: moment().subtract(15, 'minutes'), to: moment(), @@ -174,7 +174,7 @@ describe('timepicker directive', function () { expect($elem.find('.kbn-timepicker-modes .active').text().trim()).to.be('quick'); // Each of the 3 modes - let modes = ['absolute', 'relative', 'quick']; + const modes = ['absolute', 'relative', 'quick']; _.each(modes, function (mode) { $scope.setMode(mode); $scope.$digest(); @@ -215,7 +215,7 @@ describe('timepicker directive', function () { }); it('has a preview of the "from" input', function (done) { - let preview = $elem.find('.kbn-timepicker-section span[ng-show="relative.preview"]'); + const preview = $elem.find('.kbn-timepicker-section span[ng-show="relative.preview"]'); expect(preview.text()).to.be(moment().subtract(15, 'minutes').format($scope.format)); done(); }); @@ -226,7 +226,7 @@ describe('timepicker directive', function () { }); it('has a submit handler', function (done) { - let form = $elem.find('form[ng-submit="applyRelative()"]'); + const form = $elem.find('form[ng-submit="applyRelative()"]'); expect(form.length).to.be(1); done(); }); @@ -247,7 +247,7 @@ describe('timepicker directive', function () { }); it('has a dropdown bound to relative.unit that contains all of the intervals', function (done) { - let select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); + const select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); expect(select.length).to.be(1); expect(select.find('option').length).to.be(7); @@ -259,7 +259,7 @@ describe('timepicker directive', function () { }); it('has a checkbox that is checked when rounding is enabled', function (done) { - let checkbox = $elem.find('.kbn-timepicker-section input[ng-model="relative.round"]'); + const checkbox = $elem.find('.kbn-timepicker-section input[ng-model="relative.round"]'); expect(checkbox.length).to.be(1); // Rounding is disabled by default @@ -335,8 +335,8 @@ describe('timepicker directive', function () { }); it('updates the input fields when the scope variables are changed', function (done) { - let input = $elem.find('.kbn-timepicker-section input[ng-model="relative.count"]'); - let select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); + const input = $elem.find('.kbn-timepicker-section input[ng-model="relative.count"]'); + const select = $elem.find('.kbn-timepicker-section select[ng-model="relative.unit"]'); $scope.relative.count = 5; $scope.$digest(); diff --git a/src/ui/public/directives/__tests__/truncate.js b/src/ui/public/directives/__tests__/truncate.js index 1ed5f4dba3aaf..9132c2bb3b7d1 100644 --- a/src/ui/public/directives/__tests__/truncate.js +++ b/src/ui/public/directives/__tests__/truncate.js @@ -11,7 +11,7 @@ let $scope; let $elem; -let init = function (text) { +const init = function (text) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/directives/__tests__/typeahead.js b/src/ui/public/directives/__tests__/typeahead.js index 0c7424d356b3b..5e7ca60d896bb 100644 --- a/src/ui/public/directives/__tests__/typeahead.js +++ b/src/ui/public/directives/__tests__/typeahead.js @@ -7,8 +7,8 @@ import 'plugins/kibana/discover/index'; // TODO: This should not be needed, timefilter is only included here, it should move -let typeaheadHistoryCount = 10; -let typeaheadName = 'unittest'; +const typeaheadHistoryCount = 10; +const typeaheadName = 'unittest'; let $parentScope; let $typeaheadScope; let $elem; @@ -20,9 +20,9 @@ let markup = '
' + '' + '' + '
'; -let typeaheadItems = ['abc', 'def', 'ghi']; +const typeaheadItems = ['abc', 'def', 'ghi']; -let init = function () { +const init = function () { // Load the application ngMock.module('kibana'); @@ -64,7 +64,7 @@ let init = function () { describe('typeahead directive', function () { describe('typeahead requirements', function () { describe('missing input', function () { - let goodMarkup = markup; + const goodMarkup = markup; before(function () { markup = '
' + @@ -99,7 +99,7 @@ describe('typeahead directive', function () { }); it('should not save empty entries', function () { - let entries = typeaheadItems.slice(0); + const entries = typeaheadItems.slice(0); entries.push('', 'jkl'); for (let i = 0; i < entries.length; i++) { $typeaheadScope.inputModel.$setViewValue(entries[i]); @@ -129,9 +129,9 @@ describe('typeahead directive', function () { }); it('should order filtered results', function () { - let entries = ['ac/dc', 'anthrax', 'abba', 'phantogram', 'skrillex']; - let allEntries = typeaheadItems.concat(entries); - let startMatches = allEntries.filter(function (item) { + const entries = ['ac/dc', 'anthrax', 'abba', 'phantogram', 'skrillex']; + const allEntries = typeaheadItems.concat(entries); + const startMatches = allEntries.filter(function (item) { return /^a/.test(item); }); typeaheadCtrl.history.add.returns(allEntries); @@ -144,7 +144,7 @@ describe('typeahead directive', function () { typeaheadCtrl.filterItemsByQuery('a'); expect($typeaheadScope.filteredItems).to.contain('phantogram'); - let nonStarterIndex = $typeaheadScope.filteredItems.indexOf('phantogram'); + const nonStarterIndex = $typeaheadScope.filteredItems.indexOf('phantogram'); startMatches.forEach(function (item) { expect($typeaheadScope.filteredItems).to.contain(item); diff --git a/src/ui/public/directives/__tests__/validate_cidr_mask.js b/src/ui/public/directives/__tests__/validate_cidr_mask.js index 702d983ab3b35..6fd8a623d13da 100644 --- a/src/ui/public/directives/__tests__/validate_cidr_mask.js +++ b/src/ui/public/directives/__tests__/validate_cidr_mask.js @@ -7,7 +7,7 @@ import 'ui/directives/validate_cidr_mask'; describe('Validate CIDR mask directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -17,7 +17,7 @@ describe('Validate CIDR mask directive', function () { })); it('should allow empty input', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = ''; $rootScope.$digest(); @@ -33,7 +33,7 @@ describe('Validate CIDR mask directive', function () { }); it('should allow valid CIDR masks', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '0.0.0.0/1'; $rootScope.$digest(); @@ -53,7 +53,7 @@ describe('Validate CIDR mask directive', function () { }); it('should disallow invalid CIDR masks', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'hello, world'; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/validate_date_math.js b/src/ui/public/directives/__tests__/validate_date_math.js index 02385b06a4940..869686b5fb1f3 100644 --- a/src/ui/public/directives/__tests__/validate_date_math.js +++ b/src/ui/public/directives/__tests__/validate_date_math.js @@ -7,7 +7,7 @@ import 'ui/directives/validate_date_math'; describe('Validate date math directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -17,7 +17,7 @@ describe('Validate date math directive', function () { })); it('should allow valid date math', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'now'; $rootScope.$digest(); @@ -41,7 +41,7 @@ describe('Validate date math directive', function () { }); it('should disallow invalid date math', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'hello, world'; $rootScope.$digest(); @@ -61,7 +61,7 @@ describe('Validate date math directive', function () { }); it('should allow empty values', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = ''; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/validate_index_name.js b/src/ui/public/directives/__tests__/validate_index_name.js index 3deb454077e1e..4bd256ef15a86 100644 --- a/src/ui/public/directives/__tests__/validate_index_name.js +++ b/src/ui/public/directives/__tests__/validate_index_name.js @@ -8,8 +8,8 @@ import 'ui/directives/validate_index_name'; describe('Validate index name directive', function () { let $compile; let $rootScope; - let noWildcardHtml = ''; - let allowWildcardHtml = ''; + const noWildcardHtml = ''; + const allowWildcardHtml = ''; beforeEach(ngMock.module('kibana')); @@ -20,7 +20,7 @@ describe('Validate index name directive', function () { function checkPattern(input, html) { $rootScope.indexName = input; - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.$digest(); return element; } @@ -57,7 +57,7 @@ describe('Validate index name directive', function () { badPatterns.forEach(function (pattern) { it('should not accept index pattern: ' + pattern, function () { - let element = checkPattern(pattern, noWildcardHtml); + const element = checkPattern(pattern, noWildcardHtml); expect(element.hasClass('ng-invalid')).to.be(true); expect(element.hasClass('ng-valid')).to.not.be(true); }); @@ -65,7 +65,7 @@ describe('Validate index name directive', function () { goodPatterns.forEach(function (pattern) { it('should accept index pattern: ' + pattern, function () { - let element = checkPattern(pattern, noWildcardHtml); + const element = checkPattern(pattern, noWildcardHtml); expect(element.hasClass('ng-invalid')).to.not.be(true); expect(element.hasClass('ng-valid')).to.be(true); }); @@ -73,7 +73,7 @@ describe('Validate index name directive', function () { it('should disallow wildcards by default', function () { wildcardPatterns.forEach(function (pattern) { - let element = checkPattern(pattern, noWildcardHtml); + const element = checkPattern(pattern, noWildcardHtml); expect(element.hasClass('ng-invalid')).to.be(true); expect(element.hasClass('ng-valid')).to.not.be(true); }); @@ -81,7 +81,7 @@ describe('Validate index name directive', function () { it('should allow wildcards if the allow-wildcard attribute is present', function () { wildcardPatterns.forEach(function (pattern) { - let element = checkPattern(pattern, allowWildcardHtml); + const element = checkPattern(pattern, allowWildcardHtml); expect(element.hasClass('ng-invalid')).to.not.be(true); expect(element.hasClass('ng-valid')).to.be(true); }); diff --git a/src/ui/public/directives/__tests__/validate_ip.js b/src/ui/public/directives/__tests__/validate_ip.js index 9f5066f28f8cf..6e4e3c65cff64 100644 --- a/src/ui/public/directives/__tests__/validate_ip.js +++ b/src/ui/public/directives/__tests__/validate_ip.js @@ -7,7 +7,7 @@ import 'ui/directives/validate_ip'; describe('Validate IP directive', function () { let $compile; let $rootScope; - let html = ''; + const html = ''; beforeEach(ngMock.module('kibana')); @@ -17,7 +17,7 @@ describe('Validate IP directive', function () { })); it('should allow empty input', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = ''; $rootScope.$digest(); @@ -33,7 +33,7 @@ describe('Validate IP directive', function () { }); it('should allow valid IP addresses', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = '0.0.0.0'; $rootScope.$digest(); @@ -53,7 +53,7 @@ describe('Validate IP directive', function () { }); it('should disallow invalid IP addresses', function () { - let element = $compile(html)($rootScope); + const element = $compile(html)($rootScope); $rootScope.value = 'hello, world'; $rootScope.$digest(); diff --git a/src/ui/public/directives/__tests__/validate_json.js b/src/ui/public/directives/__tests__/validate_json.js index cf2616dc4baf1..69f4ea13d987e 100644 --- a/src/ui/public/directives/__tests__/validate_json.js +++ b/src/ui/public/directives/__tests__/validate_json.js @@ -8,23 +8,23 @@ import 'ui/directives/validate_json'; let $parentScope; let $elemScope; let $elem; -let mockScope = ''; +const mockScope = ''; -let input = { +const input = { valid: '{ "test": "json input" }', invalid: 'strings are not json' }; -let markup = { +const markup = { textarea: '', input: '' }; -let init = function (type) { +const init = function (type) { // Load the application ngMock.module('kibana'); type = type || 'input'; - let elMarkup = markup[type]; + const elMarkup = markup[type]; // Create the scope ngMock.inject(function ($injector, $rootScope, $compile) { @@ -39,7 +39,7 @@ let init = function (type) { }; describe('validate-json directive', function () { - let checkValid = function (inputVal, className) { + const checkValid = function (inputVal, className) { $parentScope.mockModel = inputVal; $elem.scope().$digest(); expect($elem.hasClass(className)).to.be(true); diff --git a/src/ui/public/directives/auto_select_if_only_one.js b/src/ui/public/directives/auto_select_if_only_one.js index 2fead2be3983c..0c77ed7d7150c 100644 --- a/src/ui/public/directives/auto_select_if_only_one.js +++ b/src/ui/public/directives/auto_select_if_only_one.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('autoSelectIfOnlyOne', function ($parse) { return { @@ -7,7 +7,7 @@ module.directive('autoSelectIfOnlyOne', function ($parse) { require: 'ngModel', link: function (scope, element, attributes, ngModelCtrl) { attributes.$observe('autoSelectIfOnlyOne', function (result) { - let options = $parse(result)(scope); + const options = $parse(result)(scope); if (options && options.length === 1) { ngModelCtrl.$setViewValue(options[0]); ngModelCtrl.$render(); diff --git a/src/ui/public/directives/bread_crumbs.js b/src/ui/public/directives/bread_crumbs.js index df0f9a7c5c390..612d69c4da402 100644 --- a/src/ui/public/directives/bread_crumbs.js +++ b/src/ui/public/directives/bread_crumbs.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import chrome from 'ui/chrome/chrome'; import breadCrumbsTemplate from 'ui/partials/bread_crumbs.html'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('breadCrumbs', function () { return { diff --git a/src/ui/public/directives/click_focus.js b/src/ui/public/directives/click_focus.js index 5a005676699c8..1c84249a131af 100644 --- a/src/ui/public/directives/click_focus.js +++ b/src/ui/public/directives/click_focus.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('clickFocus', function () { return { @@ -11,7 +11,7 @@ module.directive('clickFocus', function () { restrict: 'A', link: function ($scope, $elem) { function handler() { - let focusElem = $.find('input[name=' + $scope.clickFocus + ']'); + const focusElem = $.find('input[name=' + $scope.clickFocus + ']'); if (focusElem[0]) focusElem[0].focus(); } diff --git a/src/ui/public/directives/confirm_click.js b/src/ui/public/directives/confirm_click.js index 9c83e861ee292..fc7ae54a36499 100644 --- a/src/ui/public/directives/confirm_click.js +++ b/src/ui/public/directives/confirm_click.js @@ -6,9 +6,9 @@ uiModules restrict: 'A', link: function ($scope, $elem, attrs) { $elem.bind('click', function () { - let message = attrs.confirmation || 'Are you sure?'; + const message = attrs.confirmation || 'Are you sure?'; if (window.confirm(message)) { // eslint-disable-line no-alert - let action = attrs.confirmClick; + const action = attrs.confirmClick; if (action) { $scope.$apply($scope.$eval(action)); } diff --git a/src/ui/public/directives/css_truncate.js b/src/ui/public/directives/css_truncate.js index b9541a814d2d2..718ddfdde7080 100644 --- a/src/ui/public/directives/css_truncate.js +++ b/src/ui/public/directives/css_truncate.js @@ -1,7 +1,7 @@ import $ from 'jquery'; import _ from 'lodash'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('cssTruncate', function ($timeout) { return { diff --git a/src/ui/public/directives/field_name.js b/src/ui/public/directives/field_name.js index ffeace0af0f7c..2a1837f610b2e 100644 --- a/src/ui/public/directives/field_name.js +++ b/src/ui/public/directives/field_name.js @@ -1,7 +1,7 @@ import $ from 'jquery'; import 'ui/filters/short_dots'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('fieldName', function ($compile, $rootScope, $filter) { return { @@ -13,7 +13,7 @@ module.directive('fieldName', function ($compile, $rootScope, $filter) { }, link: function ($scope, $el) { - let typeIcon = function (fieldType) { + const typeIcon = function (fieldType) { switch (fieldType) { case 'source': return ''; @@ -45,12 +45,12 @@ module.directive('fieldName', function ($compile, $rootScope, $filter) { 'field.rowCount' ], function () { - let type = $scope.field ? $scope.field.type : $scope.fieldType; - let name = $scope.field ? $scope.field.name : $scope.fieldName; - let results = $scope.field ? !$scope.field.rowCount && !$scope.field.scripted : false; - let scripted = $scope.field ? $scope.field.scripted : false; + const type = $scope.field ? $scope.field.type : $scope.fieldType; + const name = $scope.field ? $scope.field.name : $scope.fieldName; + const results = $scope.field ? !$scope.field.rowCount && !$scope.field.scripted : false; + const scripted = $scope.field ? $scope.field.scripted : false; - let displayName = $filter('shortDots')(name); + const displayName = $filter('shortDots')(name); $el .attr('title', name) diff --git a/src/ui/public/directives/file_upload.js b/src/ui/public/directives/file_upload.js index 06c4752b456bf..80c11403b5759 100644 --- a/src/ui/public/directives/file_upload.js +++ b/src/ui/public/directives/file_upload.js @@ -1,9 +1,9 @@ import _ from 'lodash'; import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); -let html = ''; +const html = ''; module.directive('fileUpload', function () { return { @@ -16,14 +16,14 @@ module.directive('fileUpload', function () { }, template: html, link: function ($scope, $elem, attrs) { - let $button = $elem.find($scope.uploadSelector); - let $dropzone = $elem.find('.dropzone'); + const $button = $elem.find($scope.uploadSelector); + const $dropzone = $elem.find('.dropzone'); const handleFile = (file) => { if (_.isUndefined(file)) return; if (_.has(attrs, 'onRead')) { - let reader = new FileReader(); + const reader = new FileReader(); reader.onload = function (e) { $scope.$apply(function () { $scope.onRead({fileContents: e.target.result}); @@ -66,7 +66,7 @@ module.directive('fileUpload', function () { $elem.append($fileInput); $fileInput.on('change', function (e) { - let target = e.srcElement || e.target; + const target = e.srcElement || e.target; if (_.get(target, 'files.length')) { handleFile(target.files[0]); } diff --git a/src/ui/public/directives/inequality.js b/src/ui/public/directives/inequality.js index b6e2ed72b0688..44b0d0e977652 100644 --- a/src/ui/public/directives/inequality.js +++ b/src/ui/public/directives/inequality.js @@ -5,8 +5,8 @@ function makeDirectiveDef(id, compare) { return { require: 'ngModel', link: function ($scope, $el, $attr, ngModel) { - let getBound = function () { return $parse($attr[id])(); }; - let defaultVal = { + const getBound = function () { return $parse($attr[id])(); }; + const defaultVal = { 'greaterThan': -Infinity, 'lessThan': Infinity }[id]; @@ -19,8 +19,8 @@ function makeDirectiveDef(id, compare) { }); function validate(val) { - let bound = !isNaN(getBound()) ? +getBound() : defaultVal; - let valid = !isNaN(bound) && !isNaN(val) && compare(val, bound); + const bound = !isNaN(getBound()) ? +getBound() : defaultVal; + const valid = !isNaN(bound) && !isNaN(val) && compare(val, bound); ngModel.$setValidity(id, valid); return val; } diff --git a/src/ui/public/directives/infinite_scroll.js b/src/ui/public/directives/infinite_scroll.js index db1f410f56ed0..4b888cbc60eac 100644 --- a/src/ui/public/directives/infinite_scroll.js +++ b/src/ui/public/directives/infinite_scroll.js @@ -1,6 +1,6 @@ import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('kbnInfiniteScroll', function () { return { @@ -9,20 +9,20 @@ module.directive('kbnInfiniteScroll', function () { more: '=' }, link: function ($scope, $element, attrs) { - let $window = $(window); + const $window = $(window); let checkTimer; function onScroll() { if (!$scope.more) return; - let winHeight = $window.height(); - let winBottom = winHeight + $window.scrollTop(); - let elTop = $element.offset().top; - let remaining = elTop - winBottom; + const winHeight = $window.height(); + const winBottom = winHeight + $window.scrollTop(); + const elTop = $element.offset().top; + const remaining = elTop - winBottom; if (remaining <= winHeight * 0.50) { $scope[$scope.$$phase ? '$eval' : '$apply'](function () { - let more = $scope.more(); + const more = $scope.more(); }); } } diff --git a/src/ui/public/directives/input_datetime.js b/src/ui/public/directives/input_datetime.js index 0559358e83093..3144182932371 100644 --- a/src/ui/public/directives/input_datetime.js +++ b/src/ui/public/directives/input_datetime.js @@ -2,7 +2,7 @@ import $ from 'jquery'; import _ from 'lodash'; import moment from 'moment'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('inputDatetime', function () { return { @@ -10,18 +10,18 @@ module.directive('inputDatetime', function () { require: 'ngModel', link: function ($scope, $elem, attrs, ngModel) { - let format = 'YYYY-MM-DD HH:mm:ss.SSS'; + const format = 'YYYY-MM-DD HH:mm:ss.SSS'; $elem.after('
' + format + '
'); // What should I make with the input from the user? - let fromUser = function (text) { - let parsed = moment(text, format); + const fromUser = function (text) { + const parsed = moment(text, format); return parsed.isValid() ? parsed : undefined; }; // How should I present the data back to the user in the input field? - let toUser = function (datetime) { + const toUser = function (datetime) { return moment(datetime).format(format); }; diff --git a/src/ui/public/directives/input_focus.js b/src/ui/public/directives/input_focus.js index c6adccfd3e7b0..ce904b459e0f1 100644 --- a/src/ui/public/directives/input_focus.js +++ b/src/ui/public/directives/input_focus.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('inputFocus', function ($timeout) { return { diff --git a/src/ui/public/directives/input_number.js b/src/ui/public/directives/input_number.js index 51b11f0b9b44d..d7b3b79794d7e 100644 --- a/src/ui/public/directives/input_number.js +++ b/src/ui/public/directives/input_number.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('inputNumber', function () { return { diff --git a/src/ui/public/directives/json_input.js b/src/ui/public/directives/json_input.js index 640b5bd887906..35066233018b8 100644 --- a/src/ui/public/directives/json_input.js +++ b/src/ui/public/directives/json_input.js @@ -15,7 +15,7 @@ uiModules function fromJSON(value) { try { value = JSON.parse(value); - let validity = !scope.$eval(attrs.requireKeys) ? true : _.keys(value).length > 0; + const validity = !scope.$eval(attrs.requireKeys) ? true : _.keys(value).length > 0; ngModelCntrl.$setValidity('json', validity); } catch (e) { ngModelCntrl.$setValidity('json', false); diff --git a/src/ui/public/directives/paginate.js b/src/ui/public/directives/paginate.js index cf11e8ac6fd0d..cd44441ce4fdf 100644 --- a/src/ui/public/directives/paginate.js +++ b/src/ui/public/directives/paginate.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import uiModules from 'ui/modules'; import paginateControlsTemplate from 'ui/partials/paginate_controls.html'; -let PER_PAGE_DEFAULT = 10; +const PER_PAGE_DEFAULT = 10; uiModules.get('kibana') .directive('paginate', function ($parse, $compile) { @@ -22,7 +22,7 @@ uiModules.get('kibana') $el.prepend($compile('')($scope)); } - let paginate = $scope.paginate; + const paginate = $scope.paginate; // add some getters to the controller powered by attributes paginate.getList = $parse(attrs.list); @@ -42,8 +42,8 @@ uiModules.get('kibana') }, controllerAs: 'paginate', controller: function ($scope) { - let self = this; - let ALL = 0; + const self = this; + const ALL = 0; self.sizeOptions = [ { title: '10', value: 10 }, @@ -62,8 +62,8 @@ uiModules.get('kibana') self.perPageProp, self.otherWidthGetter ], function (vals, oldVals) { - let intChanges = vals[0] !== oldVals[0]; - let extChanges = vals[1] !== oldVals[1]; + const intChanges = vals[0] !== oldVals[0]; + const extChanges = vals[1] !== oldVals[1]; if (intChanges) { if (!setPerPage(self.perPage)) { @@ -102,14 +102,14 @@ uiModules.get('kibana') $scope.pages = []; if (!$scope.list) return; - let perPage = _.parseInt(self.perPage); - let count = perPage ? Math.ceil($scope.list.length / perPage) : 1; + const perPage = _.parseInt(self.perPage); + const count = perPage ? Math.ceil($scope.list.length / perPage) : 1; _.times(count, function (i) { let page; if (perPage) { - let start = perPage * i; + const start = perPage * i; page = $scope.list.slice(start, start + perPage); } else { page = $scope.list.slice(0); @@ -144,7 +144,7 @@ uiModules.get('kibana') // setup the list of the other pages to link to $scope.otherPages = []; - let width = +self.otherWidthGetter($scope) || 5; + const width = +self.otherWidthGetter($scope) || 5; let left = page.i - Math.round((width - 1) / 2); let right = left + width - 1; @@ -155,14 +155,14 @@ uiModules.get('kibana') } // shift extra right nums to left - let lastI = page.count - 1; + const lastI = page.count - 1; if (right > lastI) { right = lastI; left = right - width + 1; } for (let i = left; i <= right; i++) { - let other = $scope.pages[i]; + const other = $scope.pages[i]; if (!other) continue; diff --git a/src/ui/public/directives/pretty_duration.js b/src/ui/public/directives/pretty_duration.js index 4354f4d0ebaca..8d9653f80a348 100644 --- a/src/ui/public/directives/pretty_duration.js +++ b/src/ui/public/directives/pretty_duration.js @@ -4,7 +4,7 @@ import moment from 'moment'; import 'ui/timepicker/quick_ranges'; import 'ui/timepicker/time_units'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('prettyDuration', function (config, quickRanges, timeUnits) { @@ -15,9 +15,9 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { to: '=' }, link: function ($scope, $elem) { - let dateFormat = config.get('dateFormat'); + const dateFormat = config.get('dateFormat'); - let lookupByRange = {}; + const lookupByRange = {}; _.each(quickRanges, function (frame) { lookupByRange[frame.from + ' to ' + frame.to] = frame; }); @@ -26,13 +26,13 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { let text; // If both parts are date math, try to look up a reasonable string if ($scope.from && $scope.to && !moment.isMoment($scope.from) && !moment.isMoment($scope.to)) { - let tryLookup = lookupByRange[$scope.from.toString() + ' to ' + $scope.to.toString()]; + const tryLookup = lookupByRange[$scope.from.toString() + ' to ' + $scope.to.toString()]; if (tryLookup) { $elem.text(tryLookup.display); } else { - let fromParts = $scope.from.toString().split('-'); + const fromParts = $scope.from.toString().split('-'); if ($scope.to.toString() === 'now' && fromParts[0] === 'now' && fromParts[1]) { - let rounded = fromParts[1].split('/'); + const rounded = fromParts[1].split('/'); text = 'Last ' + rounded[0]; if (rounded[1]) { text = text + ' rounded to the ' + timeUnits[rounded[1]]; @@ -49,7 +49,7 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { }; function cantLookup() { - let display = {}; + const display = {}; _.each(['from', 'to'], function (time) { if (moment.isMoment($scope[time])) { display[time] = $scope[time].format(dateFormat); @@ -57,7 +57,7 @@ module.directive('prettyDuration', function (config, quickRanges, timeUnits) { if ($scope[time] === 'now') { display[time] = 'now'; } else { - let tryParse = dateMath.parse($scope[time], time === 'to' ? true : false); + const tryParse = dateMath.parse($scope[time], time === 'to' ? true : false); display[time] = moment.isMoment(tryParse) ? '~ ' + tryParse.fromNow() : $scope[time]; } } diff --git a/src/ui/public/directives/rows.js b/src/ui/public/directives/rows.js index b9bab0cdeb7c2..7909bf102e71f 100644 --- a/src/ui/public/directives/rows.js +++ b/src/ui/public/directives/rows.js @@ -3,10 +3,10 @@ import _ from 'lodash'; import AggConfigResult from 'ui/vis/agg_config_result'; import FilterBarFilterBarClickHandlerProvider from 'ui/filter_bar/filter_bar_click_handler'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private) { - let filterBarClickHandler = Private(FilterBarFilterBarClickHandlerProvider); + const filterBarClickHandler = Private(FilterBarFilterBarClickHandlerProvider); return { restrict: 'A', link: function ($scope, $el, attr) { @@ -17,10 +17,10 @@ module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private // access to it here. This may become a problem with the switch to BigNumber if (_.isNumeric(contents)) $cell.addClass('numeric-value'); - let createAggConfigResultCell = function (aggConfigResult) { - let $cell = $(document.createElement('td')); - let $state = getAppState(); - let clickHandler = filterBarClickHandler($state); + const createAggConfigResultCell = function (aggConfigResult) { + const $cell = $(document.createElement('td')); + const $state = getAppState(); + const clickHandler = filterBarClickHandler($state); $cell.scope = $scope.$new(); $cell.addClass('cell-hover'); $cell.attr('ng-click', 'clickHandler($event)'); @@ -76,18 +76,18 @@ module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private attr.kbnRowsMin ], function (vals) { let rows = vals[0]; - let min = vals[1]; + const min = vals[1]; $el.empty(); if (!_.isArray(rows)) rows = []; - let width = rows.reduce(maxRowSize, 0); + const width = rows.reduce(maxRowSize, 0); if (isFinite(min) && rows.length < min) { // clone the rows so that we can add elements to it without upsetting the original rows = _.clone(rows); // crate the empty row which will be pushed into the row list over and over - let emptyRow = new Array(width); + const emptyRow = new Array(width); // fill the empty row with values _.times(width, function (i) { emptyRow[i] = ''; }); // push as many empty rows into the row array as needed @@ -95,7 +95,7 @@ module.directive('kbnRows', function ($compile, $rootScope, getAppState, Private } rows.forEach(function (row) { - let $tr = $(document.createElement('tr')).appendTo($el); + const $tr = $(document.createElement('tr')).appendTo($el); row.forEach(function (cell) { addCell($tr, cell); }); diff --git a/src/ui/public/directives/saved_object_finder.js b/src/ui/public/directives/saved_object_finder.js index d936f04342fd9..efa4f7ebf7fcc 100644 --- a/src/ui/public/directives/saved_object_finder.js +++ b/src/ui/public/directives/saved_object_finder.js @@ -4,11 +4,11 @@ import keymap from 'ui/utils/key_map'; import SavedObjectsSavedObjectRegistryProvider from 'ui/saved_objects/saved_object_registry'; import uiModules from 'ui/modules'; import savedObjectFinderTemplate from 'ui/partials/saved_object_finder.html'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Private, config) { - let services = Private(SavedObjectsSavedObjectRegistryProvider).byLoaderPropertiesName; + const services = Private(SavedObjectsSavedObjectRegistryProvider).byLoaderPropertiesName; return { restrict: 'E', @@ -25,16 +25,16 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr template: savedObjectFinderTemplate, controllerAs: 'finder', controller: function ($scope, $element, $timeout) { - let self = this; + const self = this; // the text input element - let $input = $element.find('input[ng-model=filter]'); + const $input = $element.find('input[ng-model=filter]'); // The number of items to show in the list $scope.perPage = config.get('savedObjects:perPage'); // the list that will hold the suggestions - let $list = $element.find('ul'); + const $list = $element.find('ul'); // the current filter string, used to check that returned results are still useful let currentFilter = $scope.filter; @@ -97,7 +97,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr $scope.userOnChoose(hit, $event); } - let url = self.makeUrl(hit); + const url = self.makeUrl(hit); if (!url || url === '#' || url.charAt(0) !== '#') return; $event.preventDefault(); @@ -135,7 +135,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr case 'enter': if (self.hitCount !== 1) return; - let hit = self.hits[0]; + const hit = self.hits[0]; if (!hit) return; self.onChoose(hit, $event); @@ -208,8 +208,8 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr case 'enter': if (!self.selector.enabled) break; - let hitIndex = ((page.number - 1) * paginate.perPage) + self.selector.index; - let hit = self.hits[hitIndex]; + const hitIndex = ((page.number - 1) * paginate.perPage) + self.selector.index; + const hit = self.hits[hitIndex]; if (!hit) break; self.onChoose(hit, $event); @@ -251,7 +251,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr // but ensure that we don't search for the same // thing twice. This is called from multiple places // and needs to be smart about when it actually searches - let filter = currentFilter; + const filter = currentFilter; if (prevSearch === filter) return; prevSearch = filter; @@ -267,7 +267,7 @@ module.directive('savedObjectFinder', function ($location, $injector, kbnUrl, Pr } function scrollIntoView($element, snapTop) { - let el = $element[0]; + const el = $element[0]; if (!el) return; diff --git a/src/ui/public/directives/validate_date_math.js b/src/ui/public/directives/validate_date_math.js index 23c601987e7cd..c433777bd8c1a 100644 --- a/src/ui/public/directives/validate_date_math.js +++ b/src/ui/public/directives/validate_date_math.js @@ -19,7 +19,7 @@ uiModules.get('kibana').directive('validateDateMath', function () { return null; } - let moment = dateMath.parse(input); + const moment = dateMath.parse(input); ngModel.$setValidity('validDateMath', moment != null && moment.isValid()); return input; } diff --git a/src/ui/public/directives/validate_index_name.js b/src/ui/public/directives/validate_index_name.js index 10b51c4dfb8fb..8bc697ad7e575 100644 --- a/src/ui/public/directives/validate_index_name.js +++ b/src/ui/public/directives/validate_index_name.js @@ -15,10 +15,10 @@ uiModules illegalCharacters.push('*'); } - let isValid = function (input) { + const isValid = function (input) { if (input == null || input === '' || input === '.' || input === '..') return false; - let match = _.find(illegalCharacters, function (character) { + const match = _.find(illegalCharacters, function (character) { return input.indexOf(character) >= 0; }); return !match; diff --git a/src/ui/public/directives/validate_json.js b/src/ui/public/directives/validate_json.js index bf4df84f69da8..82253adb9159c 100644 --- a/src/ui/public/directives/validate_json.js +++ b/src/ui/public/directives/validate_json.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import $ from 'jquery'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('validateJson', function ($compile) { return { diff --git a/src/ui/public/doc_table/__tests__/doc_table.js b/src/ui/public/doc_table/__tests__/doc_table.js index b5dc9c3dcbbf6..0bd7cf203e28d 100644 --- a/src/ui/public/doc_table/__tests__/doc_table.js +++ b/src/ui/public/doc_table/__tests__/doc_table.js @@ -23,7 +23,7 @@ let $timeout; let searchSource; -let init = function ($elem, props) { +const init = function ($elem, props) { ngMock.inject(function ($rootScope, $compile, _$timeout_) { $timeout = _$timeout_; $parentScope = $rootScope; @@ -41,7 +41,7 @@ let init = function ($elem, props) { }); }; -let destroy = function () { +const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; diff --git a/src/ui/public/doc_table/__tests__/lib/get_sort.js b/src/ui/public/doc_table/__tests__/lib/get_sort.js index 3fc141bad8336..6a0aed4b8ba08 100644 --- a/src/ui/public/doc_table/__tests__/lib/get_sort.js +++ b/src/ui/public/doc_table/__tests__/lib/get_sort.js @@ -1,5 +1,5 @@ import getSort from 'ui/doc_table/lib/get_sort'; -let defaultSort = {time: 'desc'}; +const defaultSort = {time: 'desc'}; import expect from 'expect.js'; import ngMock from 'ng_mock'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; diff --git a/src/ui/public/doc_table/__tests__/lib/rows_headers.js b/src/ui/public/doc_table/__tests__/lib/rows_headers.js index f68527482c15e..36e9b786741b9 100644 --- a/src/ui/public/doc_table/__tests__/lib/rows_headers.js +++ b/src/ui/public/doc_table/__tests__/lib/rows_headers.js @@ -28,7 +28,7 @@ describe('Doc Table', function () { })); // Sets up the directive, take an element, and a list of properties to attach to the parent scope. - let init = function ($elem, props) { + const init = function ($elem, props) { ngMock.inject(function ($compile) { _.assign($parentScope, props); $compile($elem)($parentScope); @@ -37,17 +37,17 @@ describe('Doc Table', function () { }); }; - let destroy = function () { + const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; // For testing column removing/adding for the header and the rows // - let columnTests = function (elemType, parentElem) { + const columnTests = function (elemType, parentElem) { it('should create a time column if the timefield is defined', function (done) { - let childElems = parentElem.find(elemType); + const childElems = parentElem.find(elemType); expect(childElems.length).to.be(2); done(); }); @@ -79,7 +79,7 @@ describe('Doc Table', function () { delete parentElem.scope().indexPattern.timeFieldName; parentElem.scope().$digest(); - let childElems = parentElem.find(elemType); + const childElems = parentElem.find(elemType); expect(childElems.length).to.be(1); done(); }); @@ -89,7 +89,7 @@ describe('Doc Table', function () { describe('kbnTableHeader', function () { - let $elem = angular.element( + const $elem = angular.element( '' ); @@ -120,7 +120,7 @@ describe('Doc Table', function () { }); it('should sort asc by default, then by desc if already sorting', function (done) { - let fields = ['bytes', '@timestamp']; + const fields = ['bytes', '@timestamp']; // Should not be sorted at first expect($scope.sorting).to.eql(undefined); @@ -201,7 +201,7 @@ describe('Doc Table', function () { }); describe('kbnTableRow', function () { - let $elem = angular.element( + const $elem = angular.element( ''); $el.empty(); - let init = function () { + const init = function () { createSummaryRow($scope.row, $scope.row._id); }; @@ -53,7 +53,7 @@ module.directive('kbnTableRow', function ($compile) { // toggle display of the rows details, a full list of the fields from each row $scope.toggleRow = function () { - let $detailsTr = $el.next(); + const $detailsTr = $el.next(); $scope.open = !$scope.open; @@ -90,10 +90,10 @@ module.directive('kbnTableRow', function ($compile) { // create a tr element that lists the value for each *column* function createSummaryRow(row) { - let indexPattern = $scope.indexPattern; + const indexPattern = $scope.indexPattern; // We just create a string here because its faster. - let newHtmls = [ + const newHtmls = [ openRowHtml ]; @@ -114,16 +114,16 @@ module.directive('kbnTableRow', function ($compile) { let $cells = $el.children(); newHtmls.forEach(function (html, i) { - let $cell = $cells.eq(i); + const $cell = $cells.eq(i); if ($cell.data('discover:html') === html) return; - let reuse = _.find($cells.slice(i + 1), function (cell) { + const reuse = _.find($cells.slice(i + 1), function (cell) { return $.data(cell, 'discover:html') === html; }); - let $target = reuse ? $(reuse).detach() : $(html); + const $target = reuse ? $(reuse).detach() : $(html); $target.data('discover:html', html); - let $before = $cells.eq(i - 1); + const $before = $cells.eq(i - 1); if ($before.size()) { $before.after($target); } else { @@ -151,7 +151,7 @@ module.directive('kbnTableRow', function ($compile) { * Fill an element with the value of a field */ function _displayField(row, fieldName, breakWords) { - let indexPattern = $scope.indexPattern; + const indexPattern = $scope.indexPattern; let text = indexPattern.formatField(row, fieldName); if (breakWords) { diff --git a/src/ui/public/doc_table/doc_table.js b/src/ui/public/doc_table/doc_table.js index db3148a831525..c54e78f54724c 100644 --- a/src/ui/public/doc_table/doc_table.js +++ b/src/ui/public/doc_table/doc_table.js @@ -25,15 +25,15 @@ uiModules.get('kibana') filter: '=?', }, link: function ($scope) { - let notify = new Notifier(); + const notify = new Notifier(); $scope.limit = 50; $scope.persist = { sorting: $scope.sorting, columns: $scope.columns }; - let prereq = (function () { - let fns = []; + const prereq = (function () { + const fns = []; return function register(fn) { fns.push(fn); @@ -59,7 +59,7 @@ uiModules.get('kibana') $scope.$watch('columns', function (columns) { if (columns.length !== 0) return; - let $state = getAppState(); + const $state = getAppState(); $scope.columns.push('_source'); if ($state) $state.replace(); }); diff --git a/src/ui/public/doc_table/lib/get_sort.js b/src/ui/public/doc_table/lib/get_sort.js index e9f99615b1fce..c0124132083c7 100644 --- a/src/ui/public/doc_table/lib/get_sort.js +++ b/src/ui/public/doc_table/lib/get_sort.js @@ -7,7 +7,7 @@ import _ from 'lodash'; * @returns {object} a sort object suitable for returning to elasticsearch */ function getSort(sort, indexPattern) { - let sortObj = {}; + const sortObj = {}; let field; let direction; diff --git a/src/ui/public/doc_title/__tests__/doc_title.js b/src/ui/public/doc_title/__tests__/doc_title.js index faf38f9521473..104b3032dcadf 100644 --- a/src/ui/public/doc_title/__tests__/doc_title.js +++ b/src/ui/public/doc_title/__tests__/doc_title.js @@ -6,7 +6,7 @@ import DocTitleProvider from 'ui/doc_title'; describe('docTitle Service', function () { let initialDocTitle; - let MAIN_TITLE = 'Kibana 4'; + const MAIN_TITLE = 'Kibana 4'; let docTitle; let $rootScope; @@ -36,9 +36,9 @@ describe('docTitle Service', function () { describe('setup', function () { it('resets the title when a route change begins', function () { - let spy = $rootScope.$on; + const spy = $rootScope.$on; - let found = spy.args.some(function (args) { + const found = spy.args.some(function (args) { return args[0] === '$routeChangeStart' && args[1] === docTitle.reset; }); diff --git a/src/ui/public/doc_title/doc_title.js b/src/ui/public/doc_title/doc_title.js index 6f58e162ae5e5..32a1b4744d8d8 100644 --- a/src/ui/public/doc_title/doc_title.js +++ b/src/ui/public/doc_title/doc_title.js @@ -10,15 +10,15 @@ uiModules.get('kibana') $rootScope.$on('$routeChangeSuccess', docTitle.update); }) .service('docTitle', function ($rootScope) { - let baseTitle = document.title; - let self = this; + const baseTitle = document.title; + const self = this; let lastChange; function render() { lastChange = lastChange || []; - let parts = [lastChange[0]]; + const parts = [lastChange[0]]; if (!lastChange[1]) parts.push(baseTitle); diff --git a/src/ui/public/factories/__tests__/base_object.js b/src/ui/public/factories/__tests__/base_object.js index 758ba090d679c..de7815130962e 100644 --- a/src/ui/public/factories/__tests__/base_object.js +++ b/src/ui/public/factories/__tests__/base_object.js @@ -16,31 +16,31 @@ describe('Base Object', function () { })); it('should take an inital set of values', function () { - let baseObject = new BaseObject({ message: 'test' }); + const baseObject = new BaseObject({ message: 'test' }); expect(baseObject).to.have.property('message', 'test'); }); it('should serialize _attributes to RISON', function () { - let baseObject = new BaseObject(); + const baseObject = new BaseObject(); baseObject.message = 'Testing... 1234'; - let rison = baseObject.toRISON(); + const rison = baseObject.toRISON(); expect(rison).to.equal('(message:\'Testing... 1234\')'); }); it('should not serialize $$attributes to RISON', function () { - let baseObject = new BaseObject(); + const baseObject = new BaseObject(); baseObject.$$attributes = { foo: 'bar' }; baseObject.message = 'Testing... 1234'; - let rison = baseObject.toRISON(); + const rison = baseObject.toRISON(); expect(rison).to.equal('(message:\'Testing... 1234\')'); }); it('should serialize _attributes for JSON', function () { - let baseObject = new BaseObject(); + const baseObject = new BaseObject(); baseObject.message = 'Testing... 1234'; baseObject._private = 'foo'; baseObject.$private = 'stuff'; - let json = JSON.stringify(baseObject); + const json = JSON.stringify(baseObject); expect(json).to.equal('{"message":"Testing... 1234"}'); }); diff --git a/src/ui/public/factories/__tests__/events.js b/src/ui/public/factories/__tests__/events.js index 659490bbbb126..974f07b922148 100644 --- a/src/ui/public/factories/__tests__/events.js +++ b/src/ui/public/factories/__tests__/events.js @@ -24,8 +24,8 @@ describe('Events', function () { })); it('should handle on events', function () { - let obj = new Events(); - let prom = obj.on('test', function (message) { + const obj = new Events(); + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -39,9 +39,9 @@ describe('Events', function () { function MyEventedObject() { MyEventedObject.Super.call(this); } - let obj = new MyEventedObject(); + const obj = new MyEventedObject(); - let prom = obj.on('test', function (message) { + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -51,7 +51,7 @@ describe('Events', function () { }); it('should clear events when off is called', function () { - let obj = new Events(); + const obj = new Events(); obj.on('test', _.noop); expect(obj._listeners).to.have.property('test'); expect(obj._listeners.test).to.have.length(1); @@ -60,9 +60,9 @@ describe('Events', function () { }); it('should clear a specific handler when off is called for an event', function () { - let obj = new Events(); - let handler1 = sinon.stub(); - let handler2 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); + const handler2 = sinon.stub(); obj.on('test', handler1); obj.on('test', handler2); expect(obj._listeners).to.have.property('test'); @@ -76,8 +76,8 @@ describe('Events', function () { }); it('should clear a all handlers when off is called for an event', function () { - let obj = new Events(); - let handler1 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); obj.on('test', handler1); expect(obj._listeners).to.have.property('test'); obj.off('test'); @@ -90,11 +90,11 @@ describe('Events', function () { }); it('should handle mulitple identical emits in the same tick', function () { - let obj = new Events(); - let handler1 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); obj.on('test', handler1); - let emits = [ + const emits = [ obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three') @@ -111,9 +111,9 @@ describe('Events', function () { }); it('should handle emits from the handler', function () { - let obj = new Events(); - let secondEmit = Promise.defer(); - let handler1 = sinon.spy(function () { + const obj = new Events(); + const secondEmit = Promise.defer(); + const handler1 = sinon.spy(function () { if (handler1.calledTwice) { return; } @@ -133,12 +133,12 @@ describe('Events', function () { }); it('should only emit to handlers registered before emit is called', function () { - let obj = new Events(); - let handler1 = sinon.stub(); - let handler2 = sinon.stub(); + const obj = new Events(); + const handler1 = sinon.stub(); + const handler2 = sinon.stub(); obj.on('test', handler1); - let emits = [ + const emits = [ obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three') @@ -150,7 +150,7 @@ describe('Events', function () { obj.on('test', handler2); - let emits2 = [ + const emits2 = [ obj.emit('test', 'four'), obj.emit('test', 'five'), obj.emit('test', 'six') @@ -165,9 +165,9 @@ describe('Events', function () { }); it('should pass multiple arguments from the emitter', function () { - let obj = new Events(); - let handler = sinon.stub(); - let payload = [ + const obj = new Events(); + const handler = sinon.stub(); + const payload = [ 'one', { hello: 'tests' }, null @@ -183,8 +183,8 @@ describe('Events', function () { }); it('should preserve the scope of the handler', function () { - let obj = new Events(); - let expected = 'some value'; + const obj = new Events(); + const expected = 'some value'; let testValue; function handler(arg1, arg2) { @@ -200,9 +200,9 @@ describe('Events', function () { }); it('should always emit in the same order', function () { - let handler = sinon.stub(); + const handler = sinon.stub(); - let obj = new Events(); + const obj = new Events(); obj.on('block', _.partial(handler, 'block')); obj.on('last', _.partial(handler, 'last')); diff --git a/src/ui/public/fancy_forms/fancy_forms.js b/src/ui/public/fancy_forms/fancy_forms.js index 457b1aa01442d..c96e520505678 100644 --- a/src/ui/public/fancy_forms/fancy_forms.js +++ b/src/ui/public/fancy_forms/fancy_forms.js @@ -12,16 +12,16 @@ uiModules // directive providers are arrays $delegate.forEach(function (directive) { // get metadata about all init fns - let chain = [directive.controller, DecorativeController].map(function (fn) { - let deps = $injector.annotate(fn); + const chain = [directive.controller, DecorativeController].map(function (fn) { + const deps = $injector.annotate(fn); return { deps: deps, fn: _.isArray(fn) ? _.last(fn) : fn }; }); // replace the controller with one that will setup the actual controller directive.controller = function stub() { - let allDeps = _.toArray(arguments); + const allDeps = _.toArray(arguments); return chain.reduce(function (controller, link, i) { - let deps = allDeps.splice(0, link.deps.length); + const deps = allDeps.splice(0, link.deps.length); return link.fn.apply(controller, deps) || controller; }, this); }; diff --git a/src/ui/public/fancy_forms/kbn_form_controller.js b/src/ui/public/fancy_forms/kbn_form_controller.js index c4b9f4ef19717..ccb93885a349f 100644 --- a/src/ui/public/fancy_forms/kbn_form_controller.js +++ b/src/ui/public/fancy_forms/kbn_form_controller.js @@ -7,7 +7,7 @@ import _ from 'lodash'; * @param {$scope} $scope */ function KbnFormController($scope, $element) { - let self = this; + const self = this; self.errorCount = function (predicate) { return self.$$invalidModels().length; @@ -21,14 +21,14 @@ function KbnFormController($scope, $element) { }; self.describeErrors = function () { - let count = self.softErrorCount(); + const count = self.softErrorCount(); return count + ' Error' + (count === 1 ? '' : 's'); }; self.$$invalidModels = function (predicate) { predicate = _.callback(predicate); - let invalid = []; + const invalid = []; _.forOwn(self.$error, function collect(models) { if (!models) return; diff --git a/src/ui/public/field_editor/__tests__/field_editor.js b/src/ui/public/field_editor/__tests__/field_editor.js index 366fe48ea2b56..328245e4564ac 100644 --- a/src/ui/public/field_editor/__tests__/field_editor.js +++ b/src/ui/public/field_editor/__tests__/field_editor.js @@ -50,7 +50,7 @@ describe('FieldEditor directive', function () { it('exposes $scope.editor, a controller for the editor', function () { compile(); - let editor = $scope.editor; + const editor = $scope.editor; expect(editor).to.be.an('object'); }); }); @@ -90,8 +90,8 @@ describe('FieldEditor directive', function () { }); it('reflects changes to the index patterns field', function () { - let a = {}; - let b = {}; + const a = {}; + const b = {}; actual.script = a; expect(field.script).to.be(a); @@ -101,7 +101,7 @@ describe('FieldEditor directive', function () { }); it('is fully mutable, unlike the index patterns field', function () { - let origName = actual.name; + const origName = actual.name; actual.name = 'john'; expect(actual.name).to.not.be('john'); expect(actual.name).to.be(origName); diff --git a/src/ui/public/field_editor/field_editor.js b/src/ui/public/field_editor/field_editor.js index ed66858deaf52..c322587b63162 100644 --- a/src/ui/public/field_editor/field_editor.js +++ b/src/ui/public/field_editor/field_editor.js @@ -14,8 +14,8 @@ import './field_editor.less'; uiModules .get('kibana', ['colorpicker.module']) .directive('fieldEditor', function (Private, $sce) { - let fieldFormats = Private(RegistryFieldFormatsProvider); - let Field = Private(IndexPatternsFieldProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); + const Field = Private(IndexPatternsFieldProvider); const fieldTypesByLang = { painless: ['number', 'string', 'date', 'boolean'], @@ -32,8 +32,8 @@ uiModules }, controllerAs: 'editor', controller: function ($scope, Notifier, kbnUrl, $http, $q) { - let self = this; - let notify = new Notifier({ location: 'Field Editor' }); + const self = this; + const notify = new Notifier({ location: 'Field Editor' }); self.docLinks = docLinks; getScriptingLangs().then((langs) => { @@ -55,9 +55,9 @@ uiModules self.cancel = redirectAway; self.save = function () { - let indexPattern = self.indexPattern; - let fields = indexPattern.fields; - let field = self.field.toActualField(); + const indexPattern = self.indexPattern; + const fields = indexPattern.fields; + const field = self.field.toActualField(); fields.remove({ name: field.name }); fields.push(field); @@ -76,8 +76,8 @@ uiModules }; self.delete = function () { - let indexPattern = self.indexPattern; - let field = self.field; + const indexPattern = self.indexPattern; + const field = self.field; indexPattern.fields.remove({ name: field.name }); return indexPattern.save() @@ -88,9 +88,9 @@ uiModules }; $scope.$watch('editor.selectedFormatId', function (cur, prev) { - let format = self.field.format; - let changedFormat = cur !== prev; - let missingFormat = cur && (!format || format.type.id !== cur); + const format = self.field.format; + const changedFormat = cur !== prev; + const missingFormat = cur && (!format || format.type.id !== cur); if (!changedFormat || !missingFormat) return; @@ -99,7 +99,7 @@ uiModules }); $scope.$watch('editor.formatParams', function () { - let FieldFormat = getFieldFormatType(); + const FieldFormat = getFieldFormatType(); self.field.format = new FieldFormat(self.formatParams); }, true); @@ -123,8 +123,8 @@ uiModules // copy the defined properties of the field to a plain object // which is mutable, and capture the changed seperately. function shadowCopy(field) { - let changes = {}; - let shadowProps = { + const changes = {}; + const shadowProps = { toActualField: { // bring the shadow copy out of the shadows value: function toActualField() { @@ -134,7 +134,7 @@ uiModules }; Object.getOwnPropertyNames(field).forEach(function (prop) { - let desc = Object.getOwnPropertyDescriptor(field, prop); + const desc = Object.getOwnPropertyDescriptor(field, prop); shadowProps[prop] = { enumerable: desc.enumerable, get: function () { @@ -168,7 +168,7 @@ uiModules } function initDefaultFormat() { - let def = Object.create(fieldFormats.getDefaultType(self.field.type)); + const def = Object.create(fieldFormats.getDefaultType(self.field.type)); // explicitly set to undefined to prevent inheritting the prototypes id def.id = undefined; diff --git a/src/ui/public/field_format_editor/field_format_editor.js b/src/ui/public/field_format_editor/field_format_editor.js index 962e1668397b0..85092ba9c6fe3 100644 --- a/src/ui/public/field_format_editor/field_format_editor.js +++ b/src/ui/public/field_format_editor/field_format_editor.js @@ -13,7 +13,7 @@ uiModules }, controllerAs: 'editor', controller: function ($scope) { - let self = this; + const self = this; // bind the scope values to the controller, down with $scope.values $scope.editor = this; @@ -40,7 +40,7 @@ uiModules * @return {undefined} */ $scope.$watch('editor.field.format.type', function (FieldFormat) { - let opts = FieldFormat && FieldFormat.editor; + const opts = FieldFormat && FieldFormat.editor; if (!opts) { delete self.$$pseudoDirective; @@ -67,14 +67,14 @@ uiModules }, link: function ($scope, $el) { - let scopesToTeardown = []; + const scopesToTeardown = []; function setupScope(opts) { if (typeof opts !== 'object') { return scopesToTeardown[scopesToTeardown.push($scope.$new()) - 1]; } - let isolate = scopesToTeardown[scopesToTeardown.push($scope.$new(true)) - 1]; + const isolate = scopesToTeardown[scopesToTeardown.push($scope.$new(true)) - 1]; _.forOwn(opts, function (from, to) { isolate.$bind(to, from, $scope); }); @@ -88,20 +88,20 @@ uiModules if (!directive) return $el.hide(); else $el.show(); - let askedForChild = !!directive.scope; - let reuseScope = !askedForChild && !directive.controller; + const askedForChild = !!directive.scope; + const reuseScope = !askedForChild && !directive.controller; - let $formatEditor = $('
').html(directive.template); - let $formatEditorScope = reuseScope ? $scope : setupScope(directive.scope); + const $formatEditor = $('
').html(directive.template); + const $formatEditorScope = reuseScope ? $scope : setupScope(directive.scope); if (directive.controller) { // bind the controller to the injected element - let cntrlAs = (directive.controllerAs ? ' as ' + directive.controllerAs : ''); + const cntrlAs = (directive.controllerAs ? ' as ' + directive.controllerAs : ''); $formatEditorScope.Controller = directive.controller; $formatEditor.attr('ng-controller', 'Controller' + cntrlAs); } - let attrs = {}; + const attrs = {}; let linkFns = directive.compile && directive.compile($el, attrs); if (!linkFns || _.isFunction(linkFns)) { linkFns = { diff --git a/src/ui/public/field_format_editor/pattern/pattern.js b/src/ui/public/field_format_editor/pattern/pattern.js index b13610f8c84f6..5e493c9a6807c 100644 --- a/src/ui/public/field_format_editor/pattern/pattern.js +++ b/src/ui/public/field_format_editor/pattern/pattern.js @@ -11,7 +11,7 @@ uiModules require: ['ngModel', '^fieldEditor'], scope: true, link: function ($scope, $el, attrs, cntrls) { - let ngModelCntrl = cntrls[0]; + const ngModelCntrl = cntrls[0]; $scope.$bind('inputs', attrs.inputs); $scope.$bind('placeholder', attrs.placeholder); diff --git a/src/ui/public/field_format_editor/samples/samples.js b/src/ui/public/field_format_editor/samples/samples.js index d391af37d1556..a0090bbc0e060 100644 --- a/src/ui/public/field_format_editor/samples/samples.js +++ b/src/ui/public/field_format_editor/samples/samples.js @@ -11,7 +11,7 @@ uiModules require: ['?^ngModel', '^fieldEditor'], scope: true, link: function ($scope, $el, attrs, cntrls) { - let ngModelCntrl = cntrls[0]; + const ngModelCntrl = cntrls[0]; $scope.samples = null; $scope.$bind('inputs', attrs.inputs); @@ -21,14 +21,14 @@ uiModules '[]inputs' ], function () { $scope.samples = null; - let field = $scope.editor.field; + const field = $scope.editor.field; if (!field || !field.format) { return; } Promise.try(function () { - let converter = field.format.getConverterFor('html'); + const converter = field.format.getConverterFor('html'); $scope.samples = _.map($scope.inputs, function (input) { return [input, $sce.trustAsHtml(converter(input))]; }); diff --git a/src/ui/public/filter_bar/__tests__/_add_filters.js b/src/ui/public/filter_bar/__tests__/_add_filters.js index 8265d7f2705c4..5c280ce62818d 100644 --- a/src/ui/public/filter_bar/__tests__/_add_filters.js +++ b/src/ui/public/filter_bar/__tests__/_add_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('add filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -88,7 +88,7 @@ describe('add filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); // set up the watchers, add new filters, and crank the digest loop $rootScope.$digest(); @@ -109,7 +109,7 @@ describe('add filters', function () { describe('filter reconciliation', function () { it('should de-dupe appState filters being added', function () { - let newFilter = _.cloneDeep(filters[1]); + const newFilter = _.cloneDeep(filters[1]); appState.filters = filters; $rootScope.$digest(); expect(appState.filters.length).to.be(3); @@ -120,7 +120,7 @@ describe('add filters', function () { }); it('should de-dupe globalState filters being added', function () { - let newFilter = _.cloneDeep(filters[1]); + const newFilter = _.cloneDeep(filters[1]); globalState.filters = filters; $rootScope.$digest(); expect(globalState.filters.length).to.be(3); @@ -131,16 +131,16 @@ describe('add filters', function () { }); it('should mutate global filters on appState filter changes', function () { - let idx = 1; + const idx = 1; globalState.filters = filters; $rootScope.$digest(); - let appFilter = _.cloneDeep(filters[idx]); + const appFilter = _.cloneDeep(filters[idx]); appFilter.meta.negate = true; queryFilter.addFilters(appFilter); $rootScope.$digest(); - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res).to.have.length(3); _.each(res, function (filter, i) { expect(filter.$state.store).to.be('globalState'); diff --git a/src/ui/public/filter_bar/__tests__/_get_filters.js b/src/ui/public/filter_bar/__tests__/_get_filters.js index 6c1e3ee4b140a..d7df4834988ed 100644 --- a/src/ui/public/filter_bar/__tests__/_get_filters.js +++ b/src/ui/public/filter_bar/__tests__/_get_filters.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('get filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -55,7 +55,7 @@ describe('get filters', function () { expect(res[1]).to.eql(filters[0]); // should return updated version of filters - let newFilter = { query: { match: { '_type': { query: 'nginx', type: 'phrase' } } } }; + const newFilter = { query: { match: { '_type': { query: 'nginx', type: 'phrase' } } } }; appState.filters.push(newFilter); res = queryFilter.getFilters(); @@ -66,13 +66,13 @@ describe('get filters', function () { appState.filters = [filters[0]]; globalState.filters = [filters[1]]; - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res[0].$state.store).to.be(storeNames.global); expect(res[1].$state.store).to.be(storeNames.app); }); it('should return non-null filters from specific states', function () { - let states = [ + const states = [ [ globalState, queryFilter.getGlobalFilters ], [ appState, queryFilter.getAppFilters ], ]; @@ -81,14 +81,14 @@ describe('get filters', function () { state[0].filters = filters.slice(0); expect(state[0].filters).to.contain(null); - let res = state[1](); + const res = state[1](); expect(res.length).to.be(state[0].filters.length); expect(state[0].filters).to.not.contain(null); }); }); it('should replace the state, not save it', function () { - let states = [ + const states = [ [ globalState, queryFilter.getGlobalFilters ], [ appState, queryFilter.getAppFilters ], ]; @@ -102,7 +102,7 @@ describe('get filters', function () { expect(state[0].replace.called).to.be(false); state[0].filters = filters.slice(0); - let res = state[1](); + const res = state[1](); expect(state[0].save.called).to.be(false); expect(state[0].replace.called).to.be(true); }); @@ -131,11 +131,11 @@ describe('get filters', function () { it('should skip appState filters that match globalState filters', function () { globalState.filters = filters; - let appFilter = _.cloneDeep(filters[1]); + const appFilter = _.cloneDeep(filters[1]); appState.filters.push(appFilter); // global filters should be listed first - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res).to.have.length(3); _.each(res, function (filter) { expect(filter.$state.store).to.be('globalState'); @@ -144,12 +144,12 @@ describe('get filters', function () { it('should append conflicting appState filters', function () { globalState.filters = filters; - let appFilter = _.cloneDeep(filters[1]); + const appFilter = _.cloneDeep(filters[1]); appFilter.meta.negate = true; appState.filters.push(appFilter); // global filters should be listed first - let res = queryFilter.getFilters(); + const res = queryFilter.getFilters(); expect(res).to.have.length(4); expect(res.filter(function (filter) { return filter.$state.store === storeNames.global; @@ -162,7 +162,7 @@ describe('get filters', function () { it('should not affect disabled filters', function () { // test adding to globalState globalState.filters = _.map(filters, function (filter) { - let f = _.cloneDeep(filter); + const f = _.cloneDeep(filter); f.meta.disabled = true; return f; }); @@ -172,7 +172,7 @@ describe('get filters', function () { // test adding to appState globalState.filters = _.map(filters, function (filter) { - let f = _.cloneDeep(filter); + const f = _.cloneDeep(filter); f.meta.disabled = true; return f; }); diff --git a/src/ui/public/filter_bar/__tests__/_invert_filters.js b/src/ui/public/filter_bar/__tests__/_invert_filters.js index 4148268eb4370..55760e869b1cf 100644 --- a/src/ui/public/filter_bar/__tests__/_invert_filters.js +++ b/src/ui/public/filter_bar/__tests__/_invert_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('invert filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -76,7 +76,7 @@ describe('invert filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); appState.filters = filters; // set up the watchers diff --git a/src/ui/public/filter_bar/__tests__/_pin_filters.js b/src/ui/public/filter_bar/__tests__/_pin_filters.js index 4f11d7dadcd20..c5c9da43800e5 100644 --- a/src/ui/public/filter_bar/__tests__/_pin_filters.js +++ b/src/ui/public/filter_bar/__tests__/_pin_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('pin filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -87,7 +87,7 @@ describe('pin filters', function () { }); it('should move filter from appState to globalState', function () { - let filter = appState.filters[1]; + const filter = appState.filters[1]; queryFilter.pinFilter(filter); expect(globalState.filters).to.contain(filter); @@ -96,7 +96,7 @@ describe('pin filters', function () { }); it('should move filter from globalState to appState', function () { - let filter = globalState.filters[1]; + const filter = globalState.filters[1]; queryFilter.pinFilter(filter); expect(appState.filters).to.contain(filter); @@ -106,8 +106,8 @@ describe('pin filters', function () { it('should only fire the update event', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); - let filter = appState.filters[1]; + const emitSpy = sinon.spy(queryFilter, 'emit'); + const filter = appState.filters[1]; $rootScope.$digest(); queryFilter.pinFilter(filter); @@ -131,8 +131,8 @@ describe('pin filters', function () { }); it('should swap the filters in both states', function () { - let appSample = _.sample(appState.filters); - let globalSample = _.sample(globalState.filters); + const appSample = _.sample(appState.filters); + const globalSample = _.sample(globalState.filters); queryFilter.pinAll(); expect(globalState.filters).to.have.length(5); diff --git a/src/ui/public/filter_bar/__tests__/_remove_filters.js b/src/ui/public/filter_bar/__tests__/_remove_filters.js index 1020536be3692..718aa30c11393 100644 --- a/src/ui/public/filter_bar/__tests__/_remove_filters.js +++ b/src/ui/public/filter_bar/__tests__/_remove_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('remove filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -69,7 +69,7 @@ describe('remove filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); appState.filters = filters; $rootScope.$digest(); @@ -116,7 +116,7 @@ describe('remove filters', function () { appState.filters.push(filters[2]); $rootScope.$digest(); - let missedFilter = _.cloneDeep(filters[0]); + const missedFilter = _.cloneDeep(filters[0]); missedFilter.meta = { negate: !filters[0].meta.negate }; diff --git a/src/ui/public/filter_bar/__tests__/_toggle_filters.js b/src/ui/public/filter_bar/__tests__/_toggle_filters.js index 4a7f4870654c2..9545c184ba79b 100644 --- a/src/ui/public/filter_bar/__tests__/_toggle_filters.js +++ b/src/ui/public/filter_bar/__tests__/_toggle_filters.js @@ -5,7 +5,7 @@ import sinon from 'auto-release-sinon'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('toggle filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; @@ -75,7 +75,7 @@ describe('toggle filters', function () { }); it('should fire the update and fetch events', function () { - let emitSpy = sinon.spy(queryFilter, 'emit'); + const emitSpy = sinon.spy(queryFilter, 'emit'); appState.filters = filters; $rootScope.$digest(); diff --git a/src/ui/public/filter_bar/__tests__/_update_filters.js b/src/ui/public/filter_bar/__tests__/_update_filters.js index efc813e2fff83..176f7543730db 100644 --- a/src/ui/public/filter_bar/__tests__/_update_filters.js +++ b/src/ui/public/filter_bar/__tests__/_update_filters.js @@ -5,7 +5,7 @@ import ngMock from 'ng_mock'; import MockState from 'fixtures/mock_state'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; describe('update filters', function () { - let storeNames = { + const storeNames = { app: 'appState', global: 'globalState' }; diff --git a/src/ui/public/filter_bar/__tests__/filter_bar.js b/src/ui/public/filter_bar/__tests__/filter_bar.js index 1228943506c6b..807765884ef22 100644 --- a/src/ui/public/filter_bar/__tests__/filter_bar.js +++ b/src/ui/public/filter_bar/__tests__/filter_bar.js @@ -43,7 +43,7 @@ describe('Filter Bar Directive', function () { Promise = $injector.get('Promise'); mapFilter = Private(FilterBarLibMapFilterProvider); - let queryFilter = Private(FilterBarQueryFilterProvider); + const queryFilter = Private(FilterBarQueryFilterProvider); queryFilter.getFilters = function () { return appState.filters; }; @@ -52,7 +52,7 @@ describe('Filter Bar Directive', function () { describe('Element rendering', function () { beforeEach(function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'apache' } } } }, { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'nginx' } } } }, { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }, @@ -66,7 +66,7 @@ describe('Filter Bar Directive', function () { $scope = $el.isolateScope(); }); - let off = $rootScope.$on('filterbar:updated', function () { + const off = $rootScope.$on('filterbar:updated', function () { off(); // force a nextTick so it continues *after* the $digest loop completes setTimeout(done, 0); @@ -77,7 +77,7 @@ describe('Filter Bar Directive', function () { }); it('should render all the filters in state', function () { - let filters = $el.find('.filter'); + const filters = $el.find('.filter'); expect(filters).to.have.length(5); expect($(filters[0]).find('span')[0].innerHTML).to.equal('_type:'); expect($(filters[0]).find('span')[1].innerHTML).to.equal('"apache"'); @@ -90,7 +90,7 @@ describe('Filter Bar Directive', function () { }); it('should be able to set an alias', function () { - let filter = $el.find('.filter')[4]; + const filter = $el.find('.filter')[4]; expect($(filter).find('span')[0].innerHTML).to.equal('foo'); }); diff --git a/src/ui/public/filter_bar/__tests__/push_filter.js b/src/ui/public/filter_bar/__tests__/push_filter.js index a38011f79b3c4..d166479a1c1dd 100644 --- a/src/ui/public/filter_bar/__tests__/push_filter.js +++ b/src/ui/public/filter_bar/__tests__/push_filter.js @@ -32,7 +32,7 @@ describe('Filter Bar pushFilter()', function () { })); it('should create the filters property it needed', function () { - let altState = {}; + const altState = {}; pushFilterFn(altState)(filter); expect(altState.filters).to.be.an(Array); }); diff --git a/src/ui/public/filter_bar/filter_bar.js b/src/ui/public/filter_bar/filter_bar.js index 64863b8f869c3..4be87c2a70c8d 100644 --- a/src/ui/public/filter_bar/filter_bar.js +++ b/src/ui/public/filter_bar/filter_bar.js @@ -9,17 +9,17 @@ import FilterBarLibFilterOutTimeBasedFilterProvider from 'ui/filter_bar/lib/filt import FilterBarLibChangeTimeFilterProvider from 'ui/filter_bar/lib/change_time_filter'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.directive('filterBar', function (Private, Promise, getAppState) { - let mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); - let mapFlattenAndWrapFilters = Private(FilterBarLibMapFlattenAndWrapFiltersProvider); - let extractTimeFilter = Private(FilterBarLibExtractTimeFilterProvider); - let filterOutTimeBasedFilter = Private(FilterBarLibFilterOutTimeBasedFilterProvider); - let changeTimeFilter = Private(FilterBarLibChangeTimeFilterProvider); - let queryFilter = Private(FilterBarQueryFilterProvider); - let privateFilterFieldRegex = /(^\$|meta)/; + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + const mapFlattenAndWrapFilters = Private(FilterBarLibMapFlattenAndWrapFiltersProvider); + const extractTimeFilter = Private(FilterBarLibExtractTimeFilterProvider); + const filterOutTimeBasedFilter = Private(FilterBarLibFilterOutTimeBasedFilterProvider); + const changeTimeFilter = Private(FilterBarLibChangeTimeFilterProvider); + const queryFilter = Private(FilterBarQueryFilterProvider); + const privateFilterFieldRegex = /(^\$|meta)/; return { restrict: 'E', @@ -46,7 +46,7 @@ module.directive('filterBar', function (Private, Promise, getAppState) { $scope.aceLoaded = function (editor) { editor.$blockScrolling = Infinity; - let session = editor.getSession(); + const session = editor.getSession(); session.setTabSize(2); session.setUseSoftTabs(true); }; @@ -139,7 +139,7 @@ module.directive('filterBar', function (Private, Promise, getAppState) { } function updateFilters() { - let filters = queryFilter.getFilters(); + const filters = queryFilter.getFilters(); mapAndFlattenFilters(filters).then(function (results) { // used to display the current filters in the state $scope.filters = _.sortBy(results, function (filter) { diff --git a/src/ui/public/filter_bar/filter_bar_click_handler.js b/src/ui/public/filter_bar/filter_bar_click_handler.js index 25c7ae1a3b1bf..ce4a67696cd2b 100644 --- a/src/ui/public/filter_bar/filter_bar_click_handler.js +++ b/src/ui/public/filter_bar/filter_bar_click_handler.js @@ -6,7 +6,7 @@ import findByParam from 'ui/utils/find_by_param'; export default function (Notifier) { return function ($state) { return function (event, simulate) { - let notify = new Notifier({ + const notify = new Notifier({ location: 'Filter bar' }); let aggConfigResult; @@ -23,14 +23,14 @@ export default function (Notifier) { } if (aggConfigResult) { - let isLegendLabel = !!event.point.values; + const isLegendLabel = !!event.point.values; let aggBuckets = _.filter(aggConfigResult.getPath(), { type: 'bucket' }); // For legend clicks, use the last bucket in the path if (isLegendLabel) { // series data has multiple values, use aggConfig on the first // hierarchical data values is an object with the addConfig - let aggConfig = findByParam(event.point.values, 'aggConfig'); + const aggConfig = findByParam(event.point.values, 'aggConfig'); aggBuckets = aggBuckets.filter((result) => result.aggConfig && result.aggConfig === aggConfig); } diff --git a/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js b/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js index cd596f04f4188..a33a92f0a4bf9 100644 --- a/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/change_time_filter.js @@ -18,7 +18,7 @@ describe('Filter Bar Directive', function () { })); it('should change the timefilter to match the range gt/lt', function () { - let filter = { range: { '@timestamp': { gt: 1388559600000, lt: 1388646000000 } } }; + const filter = { range: { '@timestamp': { gt: 1388559600000, lt: 1388646000000 } } }; changeTimeFilter(filter); expect(timefilter.time.mode).to.be('absolute'); expect(moment.isMoment(timefilter.time.to)).to.be(true); @@ -28,7 +28,7 @@ describe('Filter Bar Directive', function () { }); it('should change the timefilter to match the range gte/lte', function () { - let filter = { range: { '@timestamp': { gte: 1388559600000, lte: 1388646000000 } } }; + const filter = { range: { '@timestamp': { gte: 1388559600000, lte: 1388646000000 } } }; changeTimeFilter(filter); expect(timefilter.time.mode).to.be('absolute'); expect(moment.isMoment(timefilter.time.to)).to.be(true); diff --git a/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js b/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js index fc953a1b34049..e09308fa0f402 100644 --- a/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/dedup_filters.js @@ -4,43 +4,43 @@ describe('Filter Bar Directive', function () { describe('dedupFilters(existing, filters)', function () { it('should return only filters which are not in the existing', function () { - let existing = [ + const existing = [ { range: { bytes: { from: 0, to: 1024 } } }, { query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let filters = [ + const filters = [ { range: { bytes: { from: 1024, to: 2048 } } }, { query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let results = dedupFilters(existing, filters); + const results = dedupFilters(existing, filters); expect(results).to.contain(filters[0]); expect(results).to.not.contain(filters[1]); }); it('should ignore the disabed attribute when comparing ', function () { - let existing = [ + const existing = [ { range: { bytes: { from: 0, to: 1024 } } }, { meta: { disabled: true }, query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let filters = [ + const filters = [ { range: { bytes: { from: 1024, to: 2048 } } }, { query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let results = dedupFilters(existing, filters); + const results = dedupFilters(existing, filters); expect(results).to.contain(filters[0]); expect(results).to.not.contain(filters[1]); }); it('should ignore $state attribute', function () { - let existing = [ + const existing = [ { range: { bytes: { from: 0, to: 1024 } } }, { $state: { store: 'appState' }, query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let filters = [ + const filters = [ { range: { bytes: { from: 1024, to: 2048 } } }, { $state: { store: 'globalState' }, query: { match: { _term: { query: 'apache', type: 'phrase' } } } } ]; - let results = dedupFilters(existing, filters); + const results = dedupFilters(existing, filters); expect(results).to.contain(filters[0]); expect(results).to.not.contain(filters[1]); }); diff --git a/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js b/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js index d38746497fd85..fa9cc9bca027d 100644 --- a/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/extract_time_filter.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the matching filter for the defualt time field', function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }, { meta: { index: 'logstash-*' }, range: { 'time': { gt: 1388559600000, lt: 1388646000000 } } } ]; @@ -34,7 +34,7 @@ describe('Filter Bar Directive', function () { }); it('should not return the non-matching filter for the defualt time field', function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }, { meta: { index: 'logstash-*' }, range: { '@timestamp': { gt: 1388559600000, lt: 1388646000000 } } } ]; diff --git a/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js b/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js index 196b0acd2bc88..356ff3c06d1b9 100644 --- a/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js +++ b/src/ui/public/filter_bar/lib/__tests__/filter_applied_and_unwrap.js @@ -3,13 +3,13 @@ import filterAppliedAndUnwrap from 'ui/filter_bar/lib/filter_applied_and_unwrap' describe('Filter Bar Directive', function () { describe('filterAppliedAndUnwrap()', function () { - let filters = [ + const filters = [ { meta: { apply: true }, exists: { field: '_type' } }, { meta: { apply: false }, query: { query_string: { query: 'foo:bar' } } } ]; it('should filter the applied and unwrap the filter', function () { - let results = filterAppliedAndUnwrap(filters); + const results = filterAppliedAndUnwrap(filters); expect(results).to.have.length(1); expect(results[0]).to.eql(filters[0]); }); diff --git a/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js b/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js index f4a23ce6dfc3b..97b6c99004644 100644 --- a/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/filter_out_time_based_filter.js @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { })); it('should return the matching filter for the defualt time field', function (done) { - let filters = [ + const filters = [ { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }, { meta: { index: 'logstash-*' }, range: { 'time': { gt: 1388559600000, lt: 1388646000000 } } } ]; diff --git a/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js b/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js index 6dc126c323a4d..43fb21bf7c7a0 100644 --- a/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js +++ b/src/ui/public/filter_bar/lib/__tests__/generate_mapping_chain.js @@ -19,13 +19,13 @@ describe('Filter Bar Directive', function () { it('should create a chaning function which calls the next function if the promise is rejected', function (done) { - let filter = {}; - let mapping = sinon.stub(); + const filter = {}; + const mapping = sinon.stub(); mapping.returns(Promise.reject(filter)); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); next.returns(Promise.resolve('good')); - let chain = mappingChainFn(next); + const chain = mappingChainFn(next); chain(filter).then(function (result) { expect(result).to.be('good'); sinon.assert.calledOnce(next); @@ -35,12 +35,12 @@ describe('Filter Bar Directive', function () { }); it('should create a chaning function which DOES NOT call the next function if the result is resolved', function (done) { - let mapping = sinon.stub(); + const mapping = sinon.stub(); mapping.returns(Promise.resolve('good')); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); next.returns(Promise.resolve('bad')); - let chain = mappingChainFn(next); + const chain = mappingChainFn(next); chain({}).then(function (result) { expect(result).to.be('good'); sinon.assert.notCalled(next); @@ -50,11 +50,11 @@ describe('Filter Bar Directive', function () { }); it('should resolve result for the mapping function', function (done) { - let mapping = sinon.stub(); + const mapping = sinon.stub(); mapping.returns(Promise.resolve({ key: 'test', value: 'example' })); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); - let chain = mappingChainFn(next); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); + const chain = mappingChainFn(next); chain({}).then(function (result) { sinon.assert.notCalled(next); expect(result).to.eql({ key: 'test', value: 'example' }); @@ -64,11 +64,11 @@ describe('Filter Bar Directive', function () { }); it('should call the mapping function with the argument to the chain', function (done) { - let mapping = sinon.stub(); + const mapping = sinon.stub(); mapping.returns(Promise.resolve({ key: 'test', value: 'example' })); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); - let chain = mappingChainFn(next); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); + const chain = mappingChainFn(next); chain({ test: 'example' }).then(function (result) { sinon.assert.calledOnce(mapping); expect(mapping.args[0][0]).to.eql({ test: 'example' }); @@ -80,13 +80,13 @@ describe('Filter Bar Directive', function () { }); it('should resolve result for the next function', function (done) { - let filter = {}; - let mapping = sinon.stub(); + const filter = {}; + const mapping = sinon.stub(); mapping.returns(Promise.reject(filter)); - let mappingChainFn = generateMappingChain(mapping); - let next = sinon.stub(); + const mappingChainFn = generateMappingChain(mapping); + const next = sinon.stub(); next.returns(Promise.resolve({ key: 'test', value: 'example' })); - let chain = mappingChainFn(next); + const chain = mappingChainFn(next); chain(filter).then(function (result) { sinon.assert.calledOnce(mapping); sinon.assert.calledOnce(next); @@ -97,11 +97,11 @@ describe('Filter Bar Directive', function () { }); it('should reject with an error if no functions match', function (done) { - let filter = {}; - let mapping = sinon.stub(); + const filter = {}; + const mapping = sinon.stub(); mapping.returns(Promise.reject(filter)); - let mappingChainFn = generateMappingChain(mapping); - let chain = mappingChainFn(); + const mappingChainFn = generateMappingChain(mapping); + const chain = mappingChainFn(); chain(filter).catch(function (err) { expect(err).to.be.an(Error); expect(err.message).to.be('No mappings have been found for filter.'); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js b/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js index e3eca25525df3..faf39d3d60f4a 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_and_flatten_filters.js @@ -21,7 +21,7 @@ describe('Filter Bar Directive', function () { $rootScope = _$rootScope_; })); - let filters = [ + const filters = [ null, [ { meta: { index: 'logstash-*' }, exists: { field: '_type' } }, diff --git a/src/ui/public/filter_bar/lib/__tests__/map_default.js b/src/ui/public/filter_bar/lib/__tests__/map_default.js index 3bc66ac578b24..721283f51a109 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_default.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_default.js @@ -13,7 +13,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { query: { match_all: {} } }; + const filter = { query: { match_all: {} } }; mapDefault(filter).then(function (result) { expect(result).to.have.property('key', 'query'); expect(result).to.have.property('value', '{"match_all":{}}'); @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { }); it('should work with undefined filter types', function (done) { - let filter = { + const filter = { 'bool': { 'must': { 'term': { @@ -41,7 +41,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined if there is no valid key', function (done) { - let filter = { meta: {} }; + const filter = { meta: {} }; mapDefault(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_exists.js b/src/ui/public/filter_bar/lib/__tests__/map_exists.js index aaaf417d5b2ac..5fea9cea76b54 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_exists.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_exists.js @@ -13,7 +13,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { exists: { field: '_type' } }; + const filter = { exists: { field: '_type' } }; mapExists(filter).then(function (result) { expect(result).to.have.property('key', 'exists'); expect(result).to.have.property('value', '_type'); @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { query: { match: { query: 'foo' } } }; + const filter = { query: { match: { query: 'foo' } } }; mapExists(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_filter.js b/src/ui/public/filter_bar/lib/__tests__/map_filter.js index 108bc7933cb26..52641afb8d238 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_filter.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_filter.js @@ -23,7 +23,7 @@ describe('Filter Bar Directive', function () { describe('mapFilter()', function () { it('should map query filters', function (done) { - let before = { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'apache' } } } }; + const before = { meta: { index: 'logstash-*' }, query: { match: { '_type': { query: 'apache' } } } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', '_type'); @@ -36,7 +36,7 @@ describe('Filter Bar Directive', function () { }); it('should map exists filters', function (done) { - let before = { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }; + const before = { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', 'exists'); @@ -49,7 +49,7 @@ describe('Filter Bar Directive', function () { }); it('should map missing filters', function (done) { - let before = { meta: { index: 'logstash-*' }, missing: { field: '@timestamp' } }; + const before = { meta: { index: 'logstash-*' }, missing: { field: '@timestamp' } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', 'missing'); @@ -62,7 +62,7 @@ describe('Filter Bar Directive', function () { }); it('should map json filter', function (done) { - let before = { meta: { index: 'logstash-*' }, query: { match_all: {} } }; + const before = { meta: { index: 'logstash-*' }, query: { match_all: {} } }; mapFilter(before).then(function (after) { expect(after).to.have.property('meta'); expect(after.meta).to.have.property('key', 'query'); @@ -75,7 +75,7 @@ describe('Filter Bar Directive', function () { }); it('should finish with a catch', function (done) { - let before = { meta: { index: 'logstash-*' }}; + const before = { meta: { index: 'logstash-*' }}; mapFilter(before).catch(function (error) { expect(error).to.be.an(Error); expect(error.message).to.be('No mappings have been found for filter.'); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js b/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js index c817825457802..59ab36e8414b8 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_flatten_and_wrap_filters.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { $rootScope = _$rootScope_; })); - let filters = [ + const filters = [ null, [ { meta: { index: 'logstash-*' }, exists: { field: '_type' } }, diff --git a/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js b/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js index 96e891b9e8d2e..19d356a58059e 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_geo_bounding_box.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters with bounds', function (done) { - let filter = { + const filter = { meta: { index: 'logstash-*' }, @@ -50,7 +50,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapGeoBoundingBox(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_missing.js b/src/ui/public/filter_bar/lib/__tests__/map_missing.js index 6f45c43528225..f3cecf7dec34e 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_missing.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_missing.js @@ -14,7 +14,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { missing: { field: '_type' } }; + const filter = { missing: { field: '_type' } }; mapMissing(filter).then(function (result) { expect(result).to.have.property('key', 'missing'); expect(result).to.have.property('value', '_type'); @@ -24,7 +24,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { query: { match: { query: 'foo' } } }; + const filter = { query: { match: { query: 'foo' } } }; mapMissing(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_query_string.js b/src/ui/public/filter_bar/lib/__tests__/map_query_string.js index 2913e0b77a860..41995d99608d6 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_query_string.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_query_string.js @@ -12,7 +12,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { query: { query_string: { query: 'foo:bar' } } }; + const filter = { query: { query_string: { query: 'foo:bar' } } }; mapQueryString(filter).then(function (result) { expect(result).to.have.property('key', 'query'); expect(result).to.have.property('value', 'foo:bar'); @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { query: { match: { query: 'foo' } } }; + const filter = { query: { match: { query: 'foo' } } }; mapQueryString(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_range.js b/src/ui/public/filter_bar/lib/__tests__/map_range.js index 85fff761b36c4..653aedee1665b 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_range.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_range.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters with gt/lt', function (done) { - let filter = { meta: { index: 'logstash-*' }, range: { bytes: { lt: 2048, gt: 1024 } } }; + const filter = { meta: { index: 'logstash-*' }, range: { bytes: { lt: 2048, gt: 1024 } } }; mapRange(filter).then(function (result) { expect(result).to.have.property('key', 'bytes'); expect(result).to.have.property('value', '1,024 to 2,048'); @@ -32,7 +32,7 @@ describe('Filter Bar Directive', function () { }); it('should return the key and value for matching filters with gte/lte', function (done) { - let filter = { meta: { index: 'logstash-*' }, range: { bytes: { lte: 2048, gte: 1024 } } }; + const filter = { meta: { index: 'logstash-*' }, range: { bytes: { lte: 2048, gte: 1024 } } }; mapRange(filter).then(function (result) { expect(result).to.have.property('key', 'bytes'); expect(result).to.have.property('value', '1,024 to 2,048'); @@ -42,7 +42,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapRange(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/map_script.js b/src/ui/public/filter_bar/lib/__tests__/map_script.js index 214b14b6e63d6..ee2d64fae62fd 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_script.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_script.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { + const filter = { meta: { index: 'logstash-*', field: 'script number' }, script: {script: { inline: 'doc["script number"].value * 5', params: { value: 35}}} }; @@ -35,7 +35,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapScript(filter).catch(function (result) { expect(result).to.be(filter); done(); @@ -44,7 +44,7 @@ describe('Filter Bar Directive', function () { }); it('should return a value for a range/histogram filter from a scripted field', (done) => { - let filter = { + const filter = { meta: { index: 'logstash-*', formattedValue: '1,000.00 to 2,000.00', diff --git a/src/ui/public/filter_bar/lib/__tests__/map_terms.js b/src/ui/public/filter_bar/lib/__tests__/map_terms.js index f2971ad91d7ce..aac44755000b8 100644 --- a/src/ui/public/filter_bar/lib/__tests__/map_terms.js +++ b/src/ui/public/filter_bar/lib/__tests__/map_terms.js @@ -22,7 +22,7 @@ describe('Filter Bar Directive', function () { })); it('should return the key and value for matching filters', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }; + const filter = { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } } }; mapTerms(filter).then(function (result) { expect(result).to.have.property('key', '_type'); expect(result).to.have.property('value', 'apache'); @@ -32,7 +32,7 @@ describe('Filter Bar Directive', function () { }); it('should return undefined for none matching', function (done) { - let filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; + const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } } }; mapTerms(filter).catch(function (result) { expect(result).to.be(filter); done(); diff --git a/src/ui/public/filter_bar/lib/__tests__/only_disabled.js b/src/ui/public/filter_bar/lib/__tests__/only_disabled.js index e7bc342a5d8b1..f9e170b9afd1d 100644 --- a/src/ui/public/filter_bar/lib/__tests__/only_disabled.js +++ b/src/ui/public/filter_bar/lib/__tests__/only_disabled.js @@ -4,71 +4,71 @@ describe('Filter Bar Directive', function () { describe('onlyDisabled()', function () { it('should return true if all filters are disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } } ]; - let newFilters = [{ meta: { disabled: true } }]; + const newFilters = [{ meta: { disabled: true } }]; expect(onlyDisabled(newFilters, filters)).to.be(true); }); it('should return false if all filters are not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } } ]; - let newFilters = [{ meta: { disabled: false } }]; + const newFilters = [{ meta: { disabled: false } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return false if only old filters are disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } } ]; - let newFilters = [{ meta: { disabled: false } }]; + const newFilters = [{ meta: { disabled: false } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return false if new filters are not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } } ]; - let newFilters = [{ meta: { disabled: true } }]; + const newFilters = [{ meta: { disabled: true } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return true when all removed filters were disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } } ]; - let newFilters = []; + const newFilters = []; expect(onlyDisabled(newFilters, filters)).to.be(true); }); it('should return false when all removed filters were not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } } ]; - let newFilters = []; + const newFilters = []; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return true if all changed filters are disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true, negate: false } }, { meta: { disabled: true, negate: false } } ]; - let newFilters = [ + const newFilters = [ { meta: { disabled: true, negate: true } }, { meta: { disabled: true, negate: true } } ]; @@ -76,31 +76,31 @@ describe('Filter Bar Directive', function () { }); it('should return false if all filters remove were not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: true } } ]; - let newFilters = [{ meta: { disabled: false } }]; + const newFilters = [{ meta: { disabled: false } }]; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should return false when all removed filters are not disabled', function () { - let filters = [ + const filters = [ { meta: { disabled: true } }, { meta: { disabled: false } }, { meta: { disabled: true } } ]; - let newFilters = []; + const newFilters = []; expect(onlyDisabled(newFilters, filters)).to.be(false); }); it('should not throw with null filters', function () { - let filters = [ + const filters = [ null, { meta: { disabled: true } } ]; - let newFilters = []; + const newFilters = []; expect(function () { onlyDisabled(newFilters, filters); }).to.not.throwError(); diff --git a/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js b/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js index 391b2dc67dc65..dffe89f96f3c1 100644 --- a/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js +++ b/src/ui/public/filter_bar/lib/__tests__/uniq_filters.js @@ -4,16 +4,16 @@ describe('Filter Bar Directive', function () { describe('uniqFilter', function () { it('should filter out dups', function () { - let before = [ + const before = [ { query: { _type: { match: { query: 'apache', type: 'phrase' } } } }, { query: { _type: { match: { query: 'apache', type: 'phrase' } } } } ]; - let results = uniqFilters(before); + const results = uniqFilters(before); expect(results).to.have.length(1); }); it('should filter out duplicates, ignoring meta attributes', function () { - let before = [ + const before = [ { meta: { negate: true }, query: { _type: { match: { query: 'apache', type: 'phrase' } } } @@ -23,12 +23,12 @@ describe('Filter Bar Directive', function () { query: { _type: { match: { query: 'apache', type: 'phrase' } } } } ]; - let results = uniqFilters(before); + const results = uniqFilters(before); expect(results).to.have.length(1); }); it('should filter out duplicates, ignoring $state attributes', function () { - let before = [ + const before = [ { $state: { store: 'appState' }, query: { _type: { match: { query: 'apache', type: 'phrase' } } } @@ -38,7 +38,7 @@ describe('Filter Bar Directive', function () { query: { _type: { match: { query: 'apache', type: 'phrase' } } } } ]; - let results = uniqFilters(before); + const results = uniqFilters(before); expect(results).to.have.length(1); }); }); diff --git a/src/ui/public/filter_bar/lib/change_time_filter.js b/src/ui/public/filter_bar/lib/change_time_filter.js index 47e991eabe7be..cee9477f09edc 100644 --- a/src/ui/public/filter_bar/lib/change_time_filter.js +++ b/src/ui/public/filter_bar/lib/change_time_filter.js @@ -2,8 +2,8 @@ import moment from 'moment'; import _ from 'lodash'; export default function changeTimeFilterProvider(timefilter) { return function (filter) { - let key = _.keys(filter.range)[0]; - let values = filter.range[key]; + const key = _.keys(filter.range)[0]; + const values = filter.range[key]; timefilter.time.from = moment(values.gt || values.gte); timefilter.time.to = moment(values.lt || values.lte); timefilter.time.mode = 'absolute'; diff --git a/src/ui/public/filter_bar/lib/compare_filters.js b/src/ui/public/filter_bar/lib/compare_filters.js index 2cfa19e6d5345..3c903ba19c8f2 100644 --- a/src/ui/public/filter_bar/lib/compare_filters.js +++ b/src/ui/public/filter_bar/lib/compare_filters.js @@ -24,7 +24,7 @@ export default function (first, second, comparatorOptions) { }; function mapFilter(filter) { - let cleaned = _.omit(filter, excludedAttributes); + const cleaned = _.omit(filter, excludedAttributes); if (comparators.negate) cleaned.negate = filter.meta && !!filter.meta.negate; if (comparators.disabled) cleaned.disabled = filter.meta && !!filter.meta.disabled; return cleaned; diff --git a/src/ui/public/filter_bar/lib/extract_time_filter.js b/src/ui/public/filter_bar/lib/extract_time_filter.js index c13b96a4ffa25..a905cbf593c5d 100644 --- a/src/ui/public/filter_bar/lib/extract_time_filter.js +++ b/src/ui/public/filter_bar/lib/extract_time_filter.js @@ -3,12 +3,12 @@ export default function extractTimeFilterProvider(courier, Promise) { return Promise.method(function (filters) { // Assume all the index patterns are the same since they will be added // from the same visualization. - let id = _.get(filters, '[0].meta.index'); + const id = _.get(filters, '[0].meta.index'); if (id == null) return; return courier.indexPatterns.get(id).then(function (indexPattern) { - let filter = _.find(filters, function (obj) { - let key = _.keys(obj.range)[0]; + const filter = _.find(filters, function (obj) { + const key = _.keys(obj.range)[0]; return key === indexPattern.timeFieldName; }); if (filter && filter.range) { diff --git a/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js b/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js index bd033b15fd8d5..91299918558a2 100644 --- a/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js +++ b/src/ui/public/filter_bar/lib/filter_out_time_based_filter.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function filterOutTimeBaseFilter(courier, Promise) { return Promise.method(function (filters) { - let id = _.get(filters, '[0].meta.index'); + const id = _.get(filters, '[0].meta.index'); if (id == null) return; return courier.indexPatterns.get(id).then(function (indexPattern) { diff --git a/src/ui/public/filter_bar/lib/generate_mapping_chain.js b/src/ui/public/filter_bar/lib/generate_mapping_chain.js index e857804a37775..f27f4a50e2c1e 100644 --- a/src/ui/public/filter_bar/lib/generate_mapping_chain.js +++ b/src/ui/public/filter_bar/lib/generate_mapping_chain.js @@ -1,7 +1,7 @@ import _ from 'lodash'; export default function generateMappingChainProvider(Promise) { - let noop = function () { + const noop = function () { return Promise.reject(new Error('No mappings have been found for filter.')); }; diff --git a/src/ui/public/filter_bar/lib/map_and_flatten_filters.js b/src/ui/public/filter_bar/lib/map_and_flatten_filters.js index f48706eb68f88..ebaf8043e2f65 100644 --- a/src/ui/public/filter_bar/lib/map_and_flatten_filters.js +++ b/src/ui/public/filter_bar/lib/map_and_flatten_filters.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import FilterBarLibMapFilterProvider from 'ui/filter_bar/lib/map_filter'; export default function mapAndFlattenFiltersProvider(Private, Promise) { - let mapFilter = Private(FilterBarLibMapFilterProvider); + const mapFilter = Private(FilterBarLibMapFilterProvider); return function (filters) { return _(filters) .flatten() diff --git a/src/ui/public/filter_bar/lib/map_default.js b/src/ui/public/filter_bar/lib/map_default.js index e9f53ed21710e..45a3a2f84071d 100644 --- a/src/ui/public/filter_bar/lib/map_default.js +++ b/src/ui/public/filter_bar/lib/map_default.js @@ -2,15 +2,15 @@ import angular from 'angular'; import _ from 'lodash'; export default function mapDefaultProvider(Promise) { - let metaProperty = /(^\$|meta)/; + const metaProperty = /(^\$|meta)/; return function (filter) { - let key = _.find(_.keys(filter), function (key) { + const key = _.find(_.keys(filter), function (key) { return !key.match(metaProperty); }); if (key) { - let value = angular.toJson(filter[key]); + const value = angular.toJson(filter[key]); return Promise.resolve({ key: key, value: value }); } return Promise.reject(filter); diff --git a/src/ui/public/filter_bar/lib/map_filter.js b/src/ui/public/filter_bar/lib/map_filter.js index 5ff047813f9ef..76e317fb96b0d 100644 --- a/src/ui/public/filter_bar/lib/map_filter.js +++ b/src/ui/public/filter_bar/lib/map_filter.js @@ -11,7 +11,7 @@ import MapScriptProvider from './map_script'; import MapDefaultProvider from './map_default'; export default function mapFilterProvider(Promise, Private) { - let generateMappingChain = Private(GenerateMappingChainProvider); + const generateMappingChain = Private(GenerateMappingChainProvider); /** Mappers **/ @@ -29,7 +29,7 @@ export default function mapFilterProvider(Promise, Private) { // To create a new mapper you just need to create a function // that either handles the mapping operation or not // and add it here. ProTip: These are executed in order listed - let mappers = [ + const mappers = [ Private(MapMatchAllProvider), Private(MapTermsProvider), Private(MapRangeProvider), @@ -41,14 +41,14 @@ export default function mapFilterProvider(Promise, Private) { Private(MapDefaultProvider) ]; - let noop = function () { + const noop = function () { return Promise.reject(new Error('No mappings have been found for filter.')); }; // Create a chain of responsibility by reducing all the // mappers down into one function. - let mapFn = _.reduceRight(mappers, function (memo, map) { - let filterChainFn = generateMappingChain(map); + const mapFn = _.reduceRight(mappers, function (memo, map) { + const filterChainFn = generateMappingChain(map); return filterChainFn(memo); }, noop); diff --git a/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js b/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js index f86b5a6e566b1..fb2d0707deafb 100644 --- a/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js +++ b/src/ui/public/filter_bar/lib/map_flatten_and_wrap_filters.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import FilterBarLibMapAndFlattenFiltersProvider from 'ui/filter_bar/lib/map_and_flatten_filters'; export default function mapFlattenAndWrapFilters(Private) { - let mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); return function (filters) { return mapAndFlattenFilters(filters).then(function (filters) { return _.map(filters, function (filter) { diff --git a/src/ui/public/filter_bar/lib/map_range.js b/src/ui/public/filter_bar/lib/map_range.js index 5e710b0dd4560..8eeb93eb7c4fc 100644 --- a/src/ui/public/filter_bar/lib/map_range.js +++ b/src/ui/public/filter_bar/lib/map_range.js @@ -7,9 +7,9 @@ export default function mapRangeProvider(Promise, courier) { .indexPatterns .get(filter.meta.index) .then(function (indexPattern) { - let key = Object.keys(filter.range)[0]; - let convert = indexPattern.fields.byName[key].format.getConverterFor('text'); - let range = filter.range[key]; + const key = Object.keys(filter.range)[0]; + const convert = indexPattern.fields.byName[key].format.getConverterFor('text'); + const range = filter.range[key]; let left = has(range, 'gte') ? range.gte : range.gt; if (left == null) left = -Infinity; diff --git a/src/ui/public/filter_bar/lib/only_disabled.js b/src/ui/public/filter_bar/lib/only_disabled.js index 8bb7cbf23ee91..2513e0ba25566 100644 --- a/src/ui/public/filter_bar/lib/only_disabled.js +++ b/src/ui/public/filter_bar/lib/only_disabled.js @@ -1,6 +1,6 @@ import _ from 'lodash'; -let pluckDisabled = function (filter) { +const pluckDisabled = function (filter) { return _.get(filter, 'meta.disabled'); }; diff --git a/src/ui/public/filter_bar/lib/only_state_changed.js b/src/ui/public/filter_bar/lib/only_state_changed.js index 8fe0cceec830a..048e20929e6c9 100644 --- a/src/ui/public/filter_bar/lib/only_state_changed.js +++ b/src/ui/public/filter_bar/lib/only_state_changed.js @@ -1,6 +1,6 @@ import _ from 'lodash'; import compareFilters from 'ui/filter_bar/lib/compare_filters'; -let compareOptions = { disabled: true, negate: true }; +const compareOptions = { disabled: true, negate: true }; /** * Checks to see if only disabled filters have been changed @@ -8,7 +8,7 @@ let compareOptions = { disabled: true, negate: true }; */ export default function (newFilters, oldFilters) { return _.every(newFilters, function (newFilter, i) { - let match = _.find(oldFilters, function (oldFilter) { + const match = _.find(oldFilters, function (oldFilter) { return compareFilters(newFilter, oldFilter, compareOptions); }); return !!match; diff --git a/src/ui/public/filter_bar/push_filter.js b/src/ui/public/filter_bar/push_filter.js index 6375791b05826..95e524b8074f2 100644 --- a/src/ui/public/filter_bar/push_filter.js +++ b/src/ui/public/filter_bar/push_filter.js @@ -7,8 +7,8 @@ export default function () { // Hierarchical and tabular data set their aggConfigResult parameter // differently because of how the point is rewritten between the two. So // we need to check if the point.orig is set, if not use try the point.aggConfigResult - let filters = _.clone($state.filters || []); - let pendingFilter = { meta: { negate: negate, index: index }}; + const filters = _.clone($state.filters || []); + const pendingFilter = { meta: { negate: negate, index: index }}; _.extend(pendingFilter, filter); filters.push(pendingFilter); $state.filters = filters; diff --git a/src/ui/public/filter_bar/query_filter.js b/src/ui/public/filter_bar/query_filter.js index 7647586b0c44f..679bb66fcb432 100644 --- a/src/ui/public/filter_bar/query_filter.js +++ b/src/ui/public/filter_bar/query_filter.js @@ -8,21 +8,21 @@ import EventsProvider from 'ui/events'; import FilterBarLibMapAndFlattenFiltersProvider from 'ui/filter_bar/lib/map_and_flatten_filters'; export default function (Private, $rootScope, getAppState, globalState, config) { - let EventEmitter = Private(EventsProvider); - let mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); + const EventEmitter = Private(EventsProvider); + const mapAndFlattenFilters = Private(FilterBarLibMapAndFlattenFiltersProvider); - let queryFilter = new EventEmitter(); + const queryFilter = new EventEmitter(); queryFilter.getFilters = function () { - let compareOptions = { disabled: true, negate: true }; - let appFilters = queryFilter.getAppFilters(); - let globalFilters = queryFilter.getGlobalFilters(); + const compareOptions = { disabled: true, negate: true }; + const appFilters = queryFilter.getAppFilters(); + const globalFilters = queryFilter.getGlobalFilters(); return uniqFilters(globalFilters.concat(appFilters), compareOptions); }; queryFilter.getAppFilters = function () { - let appState = getAppState(); + const appState = getAppState(); if (!appState || !appState.filters) return []; // Work around for https://github.com/elastic/kibana/issues/5896 @@ -49,7 +49,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) queryFilter.addFilters = function (filters, global) { if (global === undefined) { - let configDefault = config.get('filters:pinnedByDefault'); + const configDefault = config.get('filters:pinnedByDefault'); if (configDefault === false || configDefault === true) { global = configDefault; @@ -57,8 +57,8 @@ export default function (Private, $rootScope, getAppState, globalState, config) } // Determine the state for the new filter (whether to pass the filter through other apps or not) - let appState = getAppState(); - let filterState = (global) ? globalState : appState; + const appState = getAppState(); + const filterState = (global) ? globalState : appState; if (!_.isArray(filters)) { filters = [filters]; @@ -79,8 +79,8 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @param {object} matchFilter The filter to remove */ queryFilter.removeFilter = function (matchFilter) { - let appState = getAppState(); - let filter = _.omit(matchFilter, ['$$hashKey']); + const appState = getAppState(); + const filter = _.omit(matchFilter, ['$$hashKey']); let state; let index; @@ -108,11 +108,11 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @returns {object} Promise that resolves to the new filter on a successful merge */ queryFilter.updateFilter = function (filter) { - let mergedFilter = _.assign({}, filter.source, filter.model); + const mergedFilter = _.assign({}, filter.source, filter.model); mergedFilter.meta.alias = filter.alias; //If the filter type is changed we want to discard the old type //when merging changes back in - let filterTypeReplaced = filter.model[filter.type] !== mergedFilter[filter.type]; + const filterTypeReplaced = filter.model[filter.type] !== mergedFilter[filter.type]; if (filterTypeReplaced) { delete mergedFilter[filter.type]; } @@ -124,7 +124,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) * Removes all filters */ queryFilter.removeAll = function () { - let appState = getAppState(); + const appState = getAppState(); appState.filters = []; globalState.filters = []; }; @@ -137,7 +137,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) */ queryFilter.toggleFilter = function (filter, force) { // Toggle the disabled flag - let disabled = _.isUndefined(force) ? !filter.meta.disabled : !!force; + const disabled = _.isUndefined(force) ? !filter.meta.disabled : !!force; filter.meta.disabled = disabled; return filter; }; @@ -182,20 +182,20 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @returns {object} updated filter */ queryFilter.pinFilter = function (filter, force) { - let appState = getAppState(); + const appState = getAppState(); if (!appState) return filter; // ensure that both states have a filters property if (!_.isArray(globalState.filters)) globalState.filters = []; if (!_.isArray(appState.filters)) appState.filters = []; - let appIndex = _.indexOf(appState.filters, filter); + const appIndex = _.indexOf(appState.filters, filter); if (appIndex !== -1 && force !== false) { appState.filters.splice(appIndex, 1); globalState.filters.push(filter); } else { - let globalIndex = _.indexOf(globalState.filters, filter); + const globalIndex = _.indexOf(globalState.filters, filter); if (globalIndex === -1 || force === true) return filter; @@ -226,7 +226,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) * Rids filter list of null values and replaces state if any nulls are found */ function validateStateFilters(state) { - let compacted = _.compact(state.filters); + const compacted = _.compact(state.filters); if (state.filters.length !== compacted.length) { state.filters = compacted; state.replace(); @@ -240,7 +240,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) * @returns {object} Resulting filter list, app and global combined */ function saveState() { - let appState = getAppState(); + const appState = getAppState(); if (appState) appState.save(); globalState.save(); } @@ -256,7 +256,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) // helper to run a function on all filters in all states function executeOnFilters(fn) { - let appState = getAppState(); + const appState = getAppState(); let globalFilters = []; let appFilters = []; @@ -268,13 +268,13 @@ export default function (Private, $rootScope, getAppState, globalState, config) function mergeStateFilters(gFilters, aFilters, compareOptions) { // ensure we don't mutate the filters passed in - let globalFilters = gFilters ? _.cloneDeep(gFilters) : []; - let appFilters = aFilters ? _.cloneDeep(aFilters) : []; + const globalFilters = gFilters ? _.cloneDeep(gFilters) : []; + const appFilters = aFilters ? _.cloneDeep(aFilters) : []; compareOptions = _.defaults(compareOptions || {}, { disabled: true }); // existing globalFilters should be mutated by appFilters _.each(appFilters, function (filter, i) { - let match = _.find(globalFilters, function (globalFilter) { + const match = _.find(globalFilters, function (globalFilter) { return compareFilters(globalFilter, filter, compareOptions); }); @@ -306,7 +306,7 @@ export default function (Private, $rootScope, getAppState, globalState, config) function initAppStateWatchers() { // multi watch on the app and global states - let stateWatchers = [{ + const stateWatchers = [{ fn: $rootScope.$watch, deep: true, get: queryFilter.getGlobalFilters @@ -325,14 +325,14 @@ export default function (Private, $rootScope, getAppState, globalState, config) let doFetch = false; // reconcile filter in global and app states - let filters = mergeStateFilters(next[0], next[1]); - let globalFilters = filters[0]; - let appFilters = filters[1]; - let appState = getAppState(); + const filters = mergeStateFilters(next[0], next[1]); + const globalFilters = filters[0]; + const appFilters = filters[1]; + const appState = getAppState(); // save the state, as it may have updated - let globalChanged = !_.isEqual(next[0], globalFilters); - let appChanged = !_.isEqual(next[1], appFilters); + const globalChanged = !_.isEqual(next[0], globalFilters); + const appChanged = !_.isEqual(next[1], appFilters); // the filters were changed, apply to state (re-triggers this watcher) if (globalChanged || appChanged) { @@ -359,8 +359,8 @@ export default function (Private, $rootScope, getAppState, globalState, config) let oldFilters = []; stateWatchers.forEach(function (watcher, i) { - let nextVal = next[i]; - let prevVal = prev[i]; + const nextVal = next[i]; + const prevVal = prev[i]; newFilters = newFilters.concat(nextVal); oldFilters = oldFilters.concat(prevVal); diff --git a/src/ui/public/filter_manager/__tests__/filter_manager.js b/src/ui/public/filter_manager/__tests__/filter_manager.js index a27b56ff6926c..47868a2c09b24 100644 --- a/src/ui/public/filter_manager/__tests__/filter_manager.js +++ b/src/ui/public/filter_manager/__tests__/filter_manager.js @@ -12,7 +12,7 @@ let appState; function checkAddFilters(length, comps, idx) { idx = idx || 0; - let filters = queryFilter.addFilters.getCall(idx).args[0]; + const filters = queryFilter.addFilters.getCall(idx).args[0]; expect(filters.length).to.be(length); if (!_.isArray(comps)) return; @@ -114,7 +114,7 @@ describe('Filter Manager', function () { checkAddFilters(0, null, 3); expect(appState.filters).to.have.length(2); - let scriptedField = {name: 'scriptedField', scripted: true, script: 1, lang: 'painless'}; + const scriptedField = {name: 'scriptedField', scripted: true, script: 1, lang: 'painless'}; filterManager.add(scriptedField, 1, '+', 'myIndex'); checkAddFilters(1, [{ meta: {index: 'myIndex', negate: false, field: 'scriptedField'}, diff --git a/src/ui/public/filter_manager/filter_manager.js b/src/ui/public/filter_manager/filter_manager.js index 6d8486f39dbcd..63dbfaf35053c 100644 --- a/src/ui/public/filter_manager/filter_manager.js +++ b/src/ui/public/filter_manager/filter_manager.js @@ -2,21 +2,21 @@ import _ from 'lodash'; import FilterBarQueryFilterProvider from 'ui/filter_bar/query_filter'; // Adds a filter to a passed state export default function (Private) { - let queryFilter = Private(FilterBarQueryFilterProvider); - let filterManager = {}; + const queryFilter = Private(FilterBarQueryFilterProvider); + const filterManager = {}; filterManager.add = function (field, values, operation, index) { values = _.isArray(values) ? values : [values]; - let fieldName = _.isObject(field) ? field.name : field; - let filters = _.flatten([queryFilter.getAppFilters()]); - let newFilters = []; + const fieldName = _.isObject(field) ? field.name : field; + const filters = _.flatten([queryFilter.getAppFilters()]); + const newFilters = []; - let negate = (operation === '-'); + const negate = (operation === '-'); // TODO: On array fields, negating does not negate the combination, rather all terms _.each(values, function (value) { let filter; - let existing = _.find(filters, function (filter) { + const existing = _.find(filters, function (filter) { if (!filter) return; if (fieldName === '_exists_' && filter.exists) { diff --git a/src/ui/public/filter_manager/lib/__tests__/range.js b/src/ui/public/filter_manager/lib/__tests__/range.js index 94bee0426f4b6..4b138edd012ed 100644 --- a/src/ui/public/filter_manager/lib/__tests__/range.js +++ b/src/ui/public/filter_manager/lib/__tests__/range.js @@ -54,9 +54,9 @@ describe('Filter Manager', function () { it('to use the right operator for each of gte, gt, lt and lte', function () { _.each({gte: '>=', gt: '>', lte: '<=', lt: '<'}, function (operator, key) { - let params = {}; + const params = {}; params[key] = 5; - let filter = fn(indexPattern.fields.byName['script number'], params, indexPattern); + const filter = fn(indexPattern.fields.byName['script number'], params, indexPattern); expect(filter.script.script.inline).to.be('(' + indexPattern.fields.byName['script number'].script + ')' + operator + key); expect(filter.script.script.params[key]).to.be(5); diff --git a/src/ui/public/filter_manager/lib/phrase.js b/src/ui/public/filter_manager/lib/phrase.js index b9e9cc92fa573..b25b711d696b7 100644 --- a/src/ui/public/filter_manager/lib/phrase.js +++ b/src/ui/public/filter_manager/lib/phrase.js @@ -1,6 +1,6 @@ import _ from 'lodash'; export default function buildPhraseFilter(field, value, indexPattern) { - let filter = { meta: { index: indexPattern.id} }; + const filter = { meta: { index: indexPattern.id} }; if (field.scripted) { // painless expects params.value while groovy and expression languages expect value. diff --git a/src/ui/public/filters/__tests__/field_type.js b/src/ui/public/filters/__tests__/field_type.js index 215a34be2c206..fb4676ddfd594 100644 --- a/src/ui/public/filters/__tests__/field_type.js +++ b/src/ui/public/filters/__tests__/field_type.js @@ -9,7 +9,7 @@ let filter; let types; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); @@ -59,7 +59,7 @@ describe('fieldType array filter', function () { }); it('should allow negation', function () { - let resultNames = _.pluck(filter(types, '!string'), 'name'); + const resultNames = _.pluck(filter(types, '!string'), 'name'); expect(resultNames).to.eql(['n1', 'n2', 'i1', 'd1']); }); }); diff --git a/src/ui/public/filters/__tests__/label.js b/src/ui/public/filters/__tests__/label.js index 920f6fb90f0bd..db604c0fc6413 100644 --- a/src/ui/public/filters/__tests__/label.js +++ b/src/ui/public/filters/__tests__/label.js @@ -9,7 +9,7 @@ import 'plugins/kibana/discover/index'; let filter; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/moment.js b/src/ui/public/filters/__tests__/moment.js index 1d4a330251e5b..fb05c6e2fb604 100644 --- a/src/ui/public/filters/__tests__/moment.js +++ b/src/ui/public/filters/__tests__/moment.js @@ -9,10 +9,10 @@ import 'ui/filters/moment'; let filter; let config; -let anchor = '2014-01-01T06:06:06.666'; +const anchor = '2014-01-01T06:06:06.666'; let clock; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/rison.js b/src/ui/public/filters/__tests__/rison.js index 2412d032da994..9e720bcf9a7d4 100644 --- a/src/ui/public/filters/__tests__/rison.js +++ b/src/ui/public/filters/__tests__/rison.js @@ -8,7 +8,7 @@ import 'plugins/kibana/discover/index'; let rison; let risonDecode; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); @@ -20,13 +20,13 @@ let init = function (expandable) { }; describe('rison filters', function () { - let testObj = { + const testObj = { time: { from: 'now-15m', to: 'now' } }; - let testRison = '(time:(from:now-15m,to:now))'; + const testRison = '(time:(from:now-15m,to:now))'; beforeEach(function () { init(); diff --git a/src/ui/public/filters/__tests__/short_dots.js b/src/ui/public/filters/__tests__/short_dots.js index cacfab16b8676..acd92001e0cb0 100644 --- a/src/ui/public/filters/__tests__/short_dots.js +++ b/src/ui/public/filters/__tests__/short_dots.js @@ -10,7 +10,7 @@ let filter; let config; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/start_from.js b/src/ui/public/filters/__tests__/start_from.js index 3f03605c27f3d..2377a06fd82fb 100644 --- a/src/ui/public/filters/__tests__/start_from.js +++ b/src/ui/public/filters/__tests__/start_from.js @@ -6,7 +6,7 @@ import 'ui/filters/start_from'; let filter; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/__tests__/uriescape.js b/src/ui/public/filters/__tests__/uriescape.js index 8baa7469ccf5c..4a1acfb404d29 100644 --- a/src/ui/public/filters/__tests__/uriescape.js +++ b/src/ui/public/filters/__tests__/uriescape.js @@ -7,7 +7,7 @@ import 'plugins/kibana/discover/index'; let filter; -let init = function (expandable) { +const init = function (expandable) { // Load the application ngMock.module('kibana'); diff --git a/src/ui/public/filters/_prop_filter.js b/src/ui/public/filters/_prop_filter.js index 19d817df80662..f2893127edf9b 100644 --- a/src/ui/public/filters/_prop_filter.js +++ b/src/ui/public/filters/_prop_filter.js @@ -23,7 +23,7 @@ function propFilter(prop) { if (!_.isArray(filters)) filters = filters.split(','); if (_.contains(filters, '*')) return list; - let options = filters.reduce(function (options, filter) { + const options = filters.reduce(function (options, filter) { let type = 'include'; let value = filter; @@ -38,12 +38,12 @@ function propFilter(prop) { }, {}); return list.filter(function (item) { - let value = item[prop]; + const value = item[prop]; - let excluded = options.exclude && _.contains(options.exclude, value); + const excluded = options.exclude && _.contains(options.exclude, value); if (excluded) return false; - let included = !options.include || _.contains(options.include, value); + const included = !options.include || _.contains(options.include, value); if (included) return true; return false; diff --git a/src/ui/public/filters/comma_list.js b/src/ui/public/filters/comma_list.js index febe90384585f..2b5943dae3100 100644 --- a/src/ui/public/filters/comma_list.js +++ b/src/ui/public/filters/comma_list.js @@ -13,12 +13,12 @@ uiModules * @return {String} */ return function (input, inclusive) { - let list = _.commaSeperatedList(input); + const list = _.commaSeperatedList(input); if (list.length < 2) { return list.join(''); } - let conj = inclusive ? ' and ' : ' or '; + const conj = inclusive ? ' and ' : ' or '; return list.slice(0, -1).join(', ') + conj + _.last(list); }; diff --git a/src/ui/public/filters/rison.js b/src/ui/public/filters/rison.js index a41864390dc76..264fef2373a78 100644 --- a/src/ui/public/filters/rison.js +++ b/src/ui/public/filters/rison.js @@ -1,6 +1,6 @@ import rison from 'rison-node'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.filter('rison', function () { return function (str) { diff --git a/src/ui/public/filters/trust_as_html.js b/src/ui/public/filters/trust_as_html.js index e622294557d33..428a5d82d800c 100644 --- a/src/ui/public/filters/trust_as_html.js +++ b/src/ui/public/filters/trust_as_html.js @@ -1,6 +1,6 @@ import angular from 'angular'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); // Simple filter to allow using ng-bind-html without explicitly calling $sce.trustAsHtml in a controller // (See http://goo.gl/mpj9o2) diff --git a/src/ui/public/filters/unique.js b/src/ui/public/filters/unique.js index 643ae819f591d..e85087ecb1ba8 100644 --- a/src/ui/public/filters/unique.js +++ b/src/ui/public/filters/unique.js @@ -6,7 +6,7 @@ uiModules .get('kibana') .filter('unique', function () { return function (arr) { - let list = _.unique(arr); + const list = _.unique(arr); return list; }; }); diff --git a/src/ui/public/highlight/__tests__/highlight.js b/src/ui/public/highlight/__tests__/highlight.js index 050cd99d92c27..6c71e73ec12fe 100644 --- a/src/ui/public/highlight/__tests__/highlight.js +++ b/src/ui/public/highlight/__tests__/highlight.js @@ -15,7 +15,7 @@ describe('Highlight', function () { tags = highlightTags; })); - let text = '' + + const text = '' + 'Bacon ipsum dolor amet pork loin pork cow pig beef chuck ground round shankle sirloin landjaeger kevin ' + 'venison sausage ribeye tongue. Chicken bacon ball tip pork. Brisket pork capicola spare ribs pastrami rump ' + 'sirloin, t-bone ham shoulder jerky turducken bresaola. Chicken cow beef picanha. Picanha hamburger alcatra ' + @@ -28,27 +28,27 @@ describe('Highlight', function () { }); it('should highlight a single result', function () { - let highlights = [ + const highlights = [ tags.pre + 'hamburger' + tags.post + ' alcatra cupim. Salami capicola boudin pork belly shank picanha.' ]; - let result = filter(text, highlights); + const result = filter(text, highlights); expect(result.indexOf('hamburger')).to.be.greaterThan(-1); expect(result.split('hamburger').length).to.be(text.split('hamburger').length); }); it('should highlight multiple results', function () { - let highlights = [ + const highlights = [ 'kevin venison sausage ribeye tongue. ' + tags.pre + 'Chicken' + tags.post + ' bacon ball tip pork. Brisket ' + 'pork capicola spare ribs pastrami rump sirloin, t-bone ham shoulder jerky turducken bresaola. ' + tags.pre + 'Chicken' + tags.post + ' cow beef picanha. Picanha' ]; - let result = filter(text, highlights); + const result = filter(text, highlights); expect(result.indexOf('Chicken')).to.be.greaterThan(-1); expect(result.split('Chicken').length).to.be(text.split('Chicken').length); }); it('should highlight multiple hits in a result', function () { - let highlights = [ + const highlights = [ 'Bacon ipsum dolor amet ' + tags.pre + 'pork' + tags.post + ' loin ' + '' + tags.pre + 'pork' + tags.post + ' cow pig beef chuck ground round shankle ' + 'sirloin landjaeger', @@ -58,14 +58,14 @@ describe('Highlight', function () { 'hamburger alcatra cupim. Salami capicola boudin ' + tags.pre + 'pork' + tags.post + ' ' + 'belly shank picanha.' ]; - let result = filter(text, highlights); + const result = filter(text, highlights); expect(result.indexOf('pork')).to.be.greaterThan(-1); expect(result.split('pork').length).to.be(text.split('pork').length); }); it('should accept an object and return a string containing its properties', function () { - let obj = {foo: 1, bar: 2}; - let result = filter(obj, null); + const obj = {foo: 1, bar: 2}; + const result = filter(obj, null); expect(result.indexOf('' + obj)).to.be(-1); expect(result.indexOf('foo')).to.be.greaterThan(-1); expect(result.indexOf('bar')).to.be.greaterThan(-1); diff --git a/src/ui/public/highlight/highlight.js b/src/ui/public/highlight/highlight.js index f51a3ae2bfb52..e75d433e8a6d1 100644 --- a/src/ui/public/highlight/highlight.js +++ b/src/ui/public/highlight/highlight.js @@ -3,7 +3,7 @@ import _ from 'lodash'; import angular from 'angular'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); module.filter('highlight', function (highlightTags) { return function (formatted, highlight) { @@ -13,12 +13,12 @@ module.filter('highlight', function (highlightTags) { section = _.escape(section); // Strip out the highlight tags to compare against the formatted string - let untagged = section + const untagged = section .split(highlightTags.pre).join('') .split(highlightTags.post).join(''); // Replace all highlight tags with proper html tags - let tagged = section + const tagged = section .split(highlightTags.pre).join('') .split(highlightTags.post).join(''); diff --git a/src/ui/public/highlight/highlight_tags.js b/src/ui/public/highlight/highlight_tags.js index 350357ec35b59..19e8a26c43a12 100644 --- a/src/ui/public/highlight/highlight_tags.js +++ b/src/ui/public/highlight/highlight_tags.js @@ -1,5 +1,5 @@ import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); // By default, ElasticSearch surrounds matched values in . This is not ideal because it is possible that // the value could contain in the value. We define these custom tags that we would never expect to see diff --git a/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js b/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js index 60a4b93ba6d77..773f2970fad7f 100644 --- a/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js +++ b/src/ui/public/index_patterns/__tests__/_cast_mapping_type.js @@ -20,7 +20,7 @@ describe('type normalizer (castMappingType)', function () { }); it('should cast numeric types to "number"', function () { - let types = [ + const types = [ 'float', 'double', 'integer', @@ -36,7 +36,7 @@ describe('type normalizer (castMappingType)', function () { }); it('should treat non-numeric known types as what they are', function () { - let types = [ + const types = [ 'date', 'boolean', 'ip', @@ -53,7 +53,7 @@ describe('type normalizer (castMappingType)', function () { }); it('should cast text and keyword types to "string"', function () { - let types = [ + const types = [ 'keyword', 'text' ]; diff --git a/src/ui/public/index_patterns/__tests__/_field_format.js b/src/ui/public/index_patterns/__tests__/_field_format.js index fd8eb22e9dd97..ca8fb8d90fcdf 100644 --- a/src/ui/public/index_patterns/__tests__/_field_format.js +++ b/src/ui/public/index_patterns/__tests__/_field_format.js @@ -24,14 +24,14 @@ describe('FieldFormat class', function () { describe('params', function () { it('accepts its params via the constructor', function () { - let f = new TestFormat({ foo: 'bar' }); + const f = new TestFormat({ foo: 'bar' }); expect(f.param('foo')).to.be('bar'); }); it('allows reading a clone of the params', function () { - let params = { foo: 'bar' }; - let f = new TestFormat(params); - let output = f.params(); + const params = { foo: 'bar' }; + const f = new TestFormat(params); + const output = f.params(); expect(output).to.eql(params); expect(output).to.not.be(params); }); @@ -39,29 +39,29 @@ describe('FieldFormat class', function () { describe('type', function () { it('links the constructor class to instances as the `type`', function () { - let f = new TestFormat(); + const f = new TestFormat(); expect(f.type).to.be(TestFormat); }); }); describe('toJSON', function () { it('serializes to a version a basic id and param pair', function () { - let f = new TestFormat({ foo: 'bar' }); - let ser = JSON.parse(JSON.stringify(f)); + const f = new TestFormat({ foo: 'bar' }); + const ser = JSON.parse(JSON.stringify(f)); expect(ser).to.eql({ id: 'test-format', params: { foo: 'bar' } }); }); it('removes param values that match the defaults', function () { TestFormat.paramDefaults = { foo: 'bar' }; - let f = new TestFormat({ foo: 'bar', baz: 'bar' }); - let ser = JSON.parse(JSON.stringify(f)); + const f = new TestFormat({ foo: 'bar', baz: 'bar' }); + const ser = JSON.parse(JSON.stringify(f)); expect(ser.params).to.eql({ baz: 'bar' }); }); it('removes the params entirely if they are empty', function () { - let f = new TestFormat(); - let ser = JSON.parse(JSON.stringify(f)); + const f = new TestFormat(); + const ser = JSON.parse(JSON.stringify(f)); expect(ser).to.not.have.property('params'); }); }); @@ -69,7 +69,7 @@ describe('FieldFormat class', function () { describe('converters', function () { describe('#getConverterFor', function () { it('returns a converter for a specific content type', function () { - let f = new TestFormat(); + const f = new TestFormat(); expect(f.getConverterFor('html')()).to.be.a('string'); expect(f.getConverterFor('text')()).to.be.a('string'); }); @@ -81,9 +81,9 @@ describe('FieldFormat class', function () { return 'formatted'; }; - let f = new TestFormat(); - let text = f.getConverterFor('text'); - let html = f.getConverterFor('html'); + const f = new TestFormat(); + const text = f.getConverterFor('text'); + const html = f.getConverterFor('html'); expect(text).to.not.be(html); expect(text('formatted')).to.be('formatted'); expect(html('formatted')).to.be('formatted'); @@ -95,9 +95,9 @@ describe('FieldFormat class', function () { html: _.constant('formatted html'), }; - let f = new TestFormat(); - let text = f.getConverterFor('text'); - let html = f.getConverterFor('html'); + const f = new TestFormat(); + const text = f.getConverterFor('text'); + const html = f.getConverterFor('html'); expect(text).to.not.be(html); expect(text('formatted text')).to.be('formatted text'); expect(html('formatted html')).to.be('formatted html'); @@ -105,13 +105,13 @@ describe('FieldFormat class', function () { it('does not escape the output of the text converter', function () { TestFormat.prototype._convert = _.constant(''); - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('', 'text')).to.contain('<'); }); it('does escape the output of the text converter if used in an html context', function () { TestFormat.prototype._convert = _.constant(''); - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('', 'html')).to.not.contain('<'); }); @@ -121,7 +121,7 @@ describe('FieldFormat class', function () { html: _.constant(''), }; - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('', 'text')).to.be(''); expect(f.convert('', 'html')).to.be(''); }); @@ -134,7 +134,7 @@ describe('FieldFormat class', function () { html: _.constant('html'), }; - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('val')).to.be('text'); }); @@ -144,12 +144,12 @@ describe('FieldFormat class', function () { html: _.constant('html'), }; - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert('val', 'html')).to.be('html'); }); it('formats a value as " - " when no value is specified', function () { - let f = new TestFormat(); + const f = new TestFormat(); expect(f.convert()).to.be(' - '); }); }); diff --git a/src/ui/public/index_patterns/__tests__/_index_pattern.js b/src/ui/public/index_patterns/__tests__/_index_pattern.js index 98b26aea61b06..62cecf44f061f 100644 --- a/src/ui/public/index_patterns/__tests__/_index_pattern.js +++ b/src/ui/public/index_patterns/__tests__/_index_pattern.js @@ -24,7 +24,7 @@ describe('index pattern', function () { let DocSource; let config; let docSourceResponse; - let indexPatternId = 'test-pattern'; + const indexPatternId = 'test-pattern'; let indexPattern; let calculateIndices; let $rootScope; @@ -471,7 +471,7 @@ describe('index pattern', function () { }); it('is fulfilled by id', async function () { - let indexList = await indexPattern.toIndexList(); + const indexList = await indexPattern.toIndexList(); expect(indexList).to.equal(indexPattern.id); }); }); diff --git a/src/ui/public/index_patterns/__tests__/_map_field.js b/src/ui/public/index_patterns/__tests__/_map_field.js index 3384e9c530a7c..4832d85a354d6 100644 --- a/src/ui/public/index_patterns/__tests__/_map_field.js +++ b/src/ui/public/index_patterns/__tests__/_map_field.js @@ -18,25 +18,25 @@ describe('field mapping normalizer (mapField)', function () { }); it('should return a modified copy of the object, not modify the original', function () { - let pristine = _.cloneDeep(fields['foo.bar']); - let mapped = fn(fields['foo.bar'], 'foo.bar'); + const pristine = _.cloneDeep(fields['foo.bar']); + const mapped = fn(fields['foo.bar'], 'foo.bar'); expect(fields['foo.bar']).to.not.eql(mapped); expect(fields['foo.bar']).to.eql(pristine); }); it('should not consider _id indexed unless it is', function () { - let mapped = fn(fields._id, '_id'); + const mapped = fn(fields._id, '_id'); expect(mapped.indexed).to.be(false); - let mapping = _.cloneDeep(fields._id); + const mapping = _.cloneDeep(fields._id); mapping.mapping._id.index = 'not_analyzed'; - let mapped2 = fn(mapping, '_id'); + const mapped2 = fn(mapping, '_id'); expect(mapped2.indexed).to.be(true); }); it('should always consider _timestamp to be an indexed date', function () { - let mapped = fn(fields._timestamp, '_timestamp'); + const mapped = fn(fields._timestamp, '_timestamp'); expect(mapped.indexed).to.be(true); expect(mapped.type).to.be('date'); }); @@ -51,7 +51,7 @@ describe('field mapping normalizer (mapField)', function () { }); it('should treat other values for index as true', function () { - let mapped = fn(fields.not_analyzed_field, 'not_analyzed_field'); + const mapped = fn(fields.not_analyzed_field, 'not_analyzed_field'); expect(mapped.indexed).to.be(true); }); diff --git a/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js b/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js index e2313bce95759..39f688a74fa7a 100644 --- a/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js +++ b/src/ui/public/index_patterns/__tests__/_pattern_to_wildcard.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; describe('Index pattern to wildcard', function () { - let fn = require('ui/index_patterns/_pattern_to_wildcard')(); + const fn = require('ui/index_patterns/_pattern_to_wildcard')(); it('should be a function', function () { diff --git a/src/ui/public/index_patterns/__tests__/flatten_hit.js b/src/ui/public/index_patterns/__tests__/flatten_hit.js index 632e959b263cc..882d44fafa655 100644 --- a/src/ui/public/index_patterns/__tests__/flatten_hit.js +++ b/src/ui/public/index_patterns/__tests__/flatten_hit.js @@ -13,7 +13,7 @@ describe('IndexPattern#flattenHit()', function () { beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function (Private, $injector) { - let indexPattern = { + const indexPattern = { fields: { byName: { 'message': { type: 'string' }, diff --git a/src/ui/public/index_patterns/__tests__/intervals.js b/src/ui/public/index_patterns/__tests__/intervals.js index ff486c86a68c4..78b8e082dd249 100644 --- a/src/ui/public/index_patterns/__tests__/intervals.js +++ b/src/ui/public/index_patterns/__tests__/intervals.js @@ -14,10 +14,10 @@ describe('Index Patterns', function () { })); it('should return correct indices for hourly [logstash-]YYYY.MM.DD.HH', function () { - let start = moment.utc('2014-01-01T07:00:00Z'); - let end = moment.utc('2014-01-01T08:30:00Z'); - let interval = { name: 'hours', startOf: 'hour', display: 'Hourly' }; - let list = intervals.toIndexList('[logstash-]YYYY.MM.DD.HH', interval, start, end); + const start = moment.utc('2014-01-01T07:00:00Z'); + const end = moment.utc('2014-01-01T08:30:00Z'); + const interval = { name: 'hours', startOf: 'hour', display: 'Hourly' }; + const list = intervals.toIndexList('[logstash-]YYYY.MM.DD.HH', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014.01.01.07', @@ -33,10 +33,10 @@ describe('Index Patterns', function () { }); it('should return correct indices for daily [logstash-]YYYY.MM.DD', function () { - let start = moment(1418244231248); - let end = moment(1418849261281); - let interval = { name: 'days', startOf: 'day', display: 'Daily' }; - let list = intervals.toIndexList('[logstash-]YYYY.MM.DD', interval, start, end); + const start = moment(1418244231248); + const end = moment(1418849261281); + const interval = { name: 'days', startOf: 'day', display: 'Daily' }; + const list = intervals.toIndexList('[logstash-]YYYY.MM.DD', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014.12.10', @@ -82,10 +82,10 @@ describe('Index Patterns', function () { }); it('should return correct indices for monthly [logstash-]YYYY.MM', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'months', startOf: 'month', display: 'Monthly' }; - let list = intervals.toIndexList('[logstash-]YYYY.MM', interval, start, end); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'months', startOf: 'month', display: 'Monthly' }; + const list = intervals.toIndexList('[logstash-]YYYY.MM', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014.12', @@ -106,10 +106,10 @@ describe('Index Patterns', function () { }); it('should return correct indices for yearly [logstash-]YYYY', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'years', startOf: 'year', display: 'Yearly' }; - let list = intervals.toIndexList('[logstash-]YYYY', interval, start, end); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'years', startOf: 'year', display: 'Yearly' }; + const list = intervals.toIndexList('[logstash-]YYYY', interval, start, end); expect(list).to.eql([ { index: 'logstash-2014', @@ -126,10 +126,10 @@ describe('Index Patterns', function () { context('with sortDirection=asc', function () { it('returns values in ascending order', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'years', startOf: 'year', display: 'Yearly' }; - let list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'asc'); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'years', startOf: 'year', display: 'Yearly' }; + const list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'asc'); expect(list).to.eql([ { index: 'logstash-2014', @@ -147,10 +147,10 @@ describe('Index Patterns', function () { context('with sortDirection=desc', function () { it('returns values in descending order', function () { - let start = moment.utc('2014-12-01'); - let end = moment.utc('2015-02-01'); - let interval = { name: 'years', startOf: 'year', display: 'Yearly' }; - let list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'desc'); + const start = moment.utc('2014-12-01'); + const end = moment.utc('2015-02-01'); + const interval = { name: 'years', startOf: 'year', display: 'Yearly' }; + const list = intervals.toIndexList('[logstash-]YYYY', interval, start, end, 'desc'); expect(list).to.eql([ { index: 'logstash-2015', diff --git a/src/ui/public/index_patterns/_cast_mapping_type.js b/src/ui/public/index_patterns/_cast_mapping_type.js index bfeab98c2a171..93f36b18bffc1 100644 --- a/src/ui/public/index_patterns/_cast_mapping_type.js +++ b/src/ui/public/index_patterns/_cast_mapping_type.js @@ -36,7 +36,7 @@ export default function CastMappingTypeFn() { function castMappingType(name) { if (!name) return 'unknown'; - let match = castMappingType.types.byName[name]; + const match = castMappingType.types.byName[name]; return match ? match.type : 'string'; } diff --git a/src/ui/public/index_patterns/_ensure_some.js b/src/ui/public/index_patterns/_ensure_some.js index 640046b108fcd..d1d10ee53ed47 100644 --- a/src/ui/public/index_patterns/_ensure_some.js +++ b/src/ui/public/index_patterns/_ensure_some.js @@ -1,6 +1,6 @@ import errors from 'ui/errors'; export default function EnsureSomeIndexPatternsFn(Private, Notifier, $location, kbnUrl) { - let notify = new Notifier(); + const notify = new Notifier(); return function ensureSomeIndexPatterns() { return function promiseHandler(patterns) { diff --git a/src/ui/public/index_patterns/_field.js b/src/ui/public/index_patterns/_field.js index 875463bdaeb56..a0c222211f46e 100644 --- a/src/ui/public/index_patterns/_field.js +++ b/src/ui/public/index_patterns/_field.js @@ -3,10 +3,10 @@ import IndexPatternsFieldFormatFieldFormatProvider from 'ui/index_patterns/_fiel import IndexPatternsFieldTypesProvider from 'ui/index_patterns/_field_types'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; export default function FieldObjectProvider(Private, shortDotsFilter, $rootScope, Notifier) { - let notify = new Notifier({ location: 'IndexPattern Field' }); - let FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); - let fieldTypes = Private(IndexPatternsFieldTypesProvider); - let fieldFormats = Private(RegistryFieldFormatsProvider); + const notify = new Notifier({ location: 'IndexPattern Field' }); + const FieldFormat = Private(IndexPatternsFieldFormatFieldFormatProvider); + const fieldTypes = Private(IndexPatternsFieldTypesProvider); + const fieldFormats = Private(RegistryFieldFormatsProvider); function Field(indexPattern, spec) { // unwrap old instances of Field @@ -15,7 +15,7 @@ export default function FieldObjectProvider(Private, shortDotsFilter, $rootScope // constuct this object using ObjDefine class, which // extends the Field.prototype but gets it's properties // defined using the logic below - let obj = new ObjDefine(spec, Field.prototype); + const obj = new ObjDefine(spec, Field.prototype); if (spec.name === '_source') { spec.type = '_source'; @@ -38,13 +38,13 @@ export default function FieldObjectProvider(Private, shortDotsFilter, $rootScope format = indexPattern.fieldFormatMap[spec.name] || fieldFormats.getDefaultInstance(spec.type); } - let indexed = !!spec.indexed; - let scripted = !!spec.scripted; - let sortable = spec.name === '_score' || ((indexed || scripted) && type.sortable); - let filterable = spec.name === '_id' || scripted || (indexed && type.filterable); - let searchable = !!spec.searchable || scripted; - let aggregatable = !!spec.aggregatable || scripted; - let visualizable = aggregatable; + const indexed = !!spec.indexed; + const scripted = !!spec.scripted; + const sortable = spec.name === '_score' || ((indexed || scripted) && type.sortable); + const filterable = spec.name === '_id' || scripted || (indexed && type.filterable); + const searchable = !!spec.searchable || scripted; + const aggregatable = !!spec.aggregatable || scripted; + const visualizable = aggregatable; obj.fact('name'); obj.fact('type'); diff --git a/src/ui/public/index_patterns/_field_format/content_types.js b/src/ui/public/index_patterns/_field_format/content_types.js index ed82f0210c1f0..c19edabe35669 100644 --- a/src/ui/public/index_patterns/_field_format/content_types.js +++ b/src/ui/public/index_patterns/_field_format/content_types.js @@ -3,7 +3,7 @@ import angular from 'angular'; import 'ui/highlight'; export default function contentTypesProvider(highlightFilter) { - let types = { + const types = { html: function (format, convert) { return function recurse(value, field, hit) { if (value == null) { @@ -14,10 +14,10 @@ export default function contentTypesProvider(highlightFilter) { return convert.call(format, value, field, hit); } - let subVals = value.map(function (v) { + const subVals = value.map(function (v) { return recurse(v, field, hit); }); - let useMultiLine = subVals.some(function (sub) { + const useMultiLine = subVals.some(function (sub) { return sub.indexOf('\n') > -1; }); @@ -42,7 +42,7 @@ export default function contentTypesProvider(highlightFilter) { } function fallbackHtml(value, field, hit) { - let formatted = _.escape(this.convert(value, 'text')); + const formatted = _.escape(this.convert(value, 'text')); if (!hit || !hit.highlight || !hit.highlight[field.name]) { return formatted; @@ -52,8 +52,8 @@ export default function contentTypesProvider(highlightFilter) { } function setup(format) { - let src = format._convert || {}; - let converters = format._convert = {}; + const src = format._convert || {}; + const converters = format._convert = {}; converters.text = types.text(format, src.text || fallbackText); converters.html = types.html(format, src.html || fallbackHtml); diff --git a/src/ui/public/index_patterns/_field_format/field_format.js b/src/ui/public/index_patterns/_field_format/field_format.js index 53b48c69985bd..0084cea0477cd 100644 --- a/src/ui/public/index_patterns/_field_format/field_format.js +++ b/src/ui/public/index_patterns/_field_format/field_format.js @@ -1,10 +1,10 @@ import _ from 'lodash'; import IndexPatternsFieldFormatContentTypesProvider from 'ui/index_patterns/_field_format/content_types'; export default function FieldFormatClassProvider(config, $rootScope, Private) { - let contentTypes = Private(IndexPatternsFieldFormatContentTypesProvider); + const contentTypes = Private(IndexPatternsFieldFormatContentTypesProvider); function FieldFormat(params) { - let self = this; + const self = this; // give the constructor a more appropriate name self.type = self.constructor; @@ -59,7 +59,7 @@ export default function FieldFormatClassProvider(config, $rootScope, Private) { * @return {any} */ FieldFormat.prototype.param = function (name) { - let val = this._params[name]; + const val = this._params[name]; if (val || val === false || val === 0) { // truthy, false, or 0 are fine // '', NaN, null, undefined, etc are not @@ -84,8 +84,8 @@ export default function FieldFormatClassProvider(config, $rootScope, Private) { * @return {object} */ FieldFormat.prototype.toJSON = function () { - let type = this.type; - let defaults = this._paramDefaults; + const type = this.type; + const defaults = this._paramDefaults; let params = _.transform(this._params, function (uniqParams, val, param) { if (val !== defaults[param]) { diff --git a/src/ui/public/index_patterns/_field_list.js b/src/ui/public/index_patterns/_field_list.js index 438159f334de6..ddfc65ff042a5 100644 --- a/src/ui/public/index_patterns/_field_list.js +++ b/src/ui/public/index_patterns/_field_list.js @@ -2,7 +2,7 @@ import IndexedArray from 'ui/indexed_array'; import _ from 'lodash'; import IndexPatternsFieldProvider from 'ui/index_patterns/_field'; export default function FieldListProvider(Private) { - let Field = Private(IndexPatternsFieldProvider); + const Field = Private(IndexPatternsFieldProvider); _.class(FieldList).inherits(IndexedArray); function FieldList(indexPattern, specs) { diff --git a/src/ui/public/index_patterns/_flatten_hit.js b/src/ui/public/index_patterns/_flatten_hit.js index 7d137cfd070e6..c757789885138 100644 --- a/src/ui/public/index_patterns/_flatten_hit.js +++ b/src/ui/public/index_patterns/_flatten_hit.js @@ -9,10 +9,10 @@ export default function FlattenHitProvider(config) { }); function flattenHit(indexPattern, hit) { - let flat = {}; + const flat = {}; // recursively merge _source - let fields = indexPattern.fields.byName; + const fields = indexPattern.fields.byName; (function flatten(obj, keyPrefix) { keyPrefix = keyPrefix ? keyPrefix + '.' : ''; _.forOwn(obj, function (val, key) { @@ -20,8 +20,8 @@ export default function FlattenHitProvider(config) { if (flat[key] !== void 0) return; - let hasValidMapping = (fields[key] && fields[key].type !== 'conflict'); - let isValue = !_.isPlainObject(val); + const hasValidMapping = (fields[key] && fields[key].type !== 'conflict'); + const isValue = !_.isPlainObject(val); if (hasValidMapping || isValue) { flat[key] = val; diff --git a/src/ui/public/index_patterns/_format_hit.js b/src/ui/public/index_patterns/_format_hit.js index d188952f33532..6f705da8b77b4 100644 --- a/src/ui/public/index_patterns/_format_hit.js +++ b/src/ui/public/index_patterns/_format_hit.js @@ -5,7 +5,7 @@ import _ from 'lodash'; export default function (indexPattern, defaultFormat) { function convert(hit, val, fieldName) { - let field = indexPattern.fields.byName[fieldName]; + const field = indexPattern.fields.byName[fieldName]; if (!field) return defaultFormat.convert(val, 'html'); return field.format.getConverterFor('html')(val, field, hit); } @@ -15,12 +15,12 @@ export default function (indexPattern, defaultFormat) { // use and update the partial cache, but don't rewrite it. _source is stored in partials // but not $$_formatted - let partials = hit.$$_partialFormatted || (hit.$$_partialFormatted = {}); - let cache = hit.$$_formatted = {}; + const partials = hit.$$_partialFormatted || (hit.$$_partialFormatted = {}); + const cache = hit.$$_formatted = {}; _.forOwn(indexPattern.flattenHit(hit), function (val, fieldName) { // sync the formatted and partial cache - let formatted = partials[fieldName] == null ? convert(hit, val, fieldName) : partials[fieldName]; + const formatted = partials[fieldName] == null ? convert(hit, val, fieldName) : partials[fieldName]; cache[fieldName] = partials[fieldName] = formatted; }); @@ -37,7 +37,7 @@ export default function (indexPattern, defaultFormat) { partials = hit.$$_partialFormatted = {}; } - let val = fieldName === '_source' ? hit._source : indexPattern.flattenHit(hit)[fieldName]; + const val = fieldName === '_source' ? hit._source : indexPattern.flattenHit(hit)[fieldName]; return partials[fieldName] = convert(hit, val, fieldName); }; diff --git a/src/ui/public/index_patterns/_get_computed_fields.js b/src/ui/public/index_patterns/_get_computed_fields.js index 3038c5e55468e..6659d492e71d7 100644 --- a/src/ui/public/index_patterns/_get_computed_fields.js +++ b/src/ui/public/index_patterns/_get_computed_fields.js @@ -2,8 +2,8 @@ import _ from 'lodash'; // Takes a hit, merges it with any stored/scripted fields, and with the metaFields // returns a flattened version export default function () { - let self = this; - let scriptFields = {}; + const self = this; + const scriptFields = {}; let docvalueFields = []; docvalueFields = _.map(_.reject(self.fields.byType.date, 'scripted'), 'name'); diff --git a/src/ui/public/index_patterns/_get_ids.js b/src/ui/public/index_patterns/_get_ids.js index b499b1dd3859d..969e186a4fb4e 100644 --- a/src/ui/public/index_patterns/_get_ids.js +++ b/src/ui/public/index_patterns/_get_ids.js @@ -5,7 +5,7 @@ export default function GetIndexPatternIdsFn(es, kbnIndex) { // didn't incorportate with the indexPattern cache to prevent id collisions. let cachedPromise; - let getIds = function () { + const getIds = function () { if (cachedPromise) { // retrun a clone of the cached response return cachedPromise.then(function (cachedResp) { diff --git a/src/ui/public/index_patterns/_intervals.js b/src/ui/public/index_patterns/_intervals.js index 89617306db719..8fe028348be19 100644 --- a/src/ui/public/index_patterns/_intervals.js +++ b/src/ui/public/index_patterns/_intervals.js @@ -3,7 +3,7 @@ import moment from 'moment'; import IndexedArray from 'ui/indexed_array'; export default function IndexNameIntervalsService(timefilter) { - let intervals = new IndexedArray({ + const intervals = new IndexedArray({ index: ['name'], initialSet: [ { @@ -40,10 +40,10 @@ export default function IndexNameIntervalsService(timefilter) { // setup the range that the list will span, return two moment objects that // are in proper order. a and b can be numbers to specify to go before or after now (respectively) // a certain number of times, based on the interval - let range = [[a, 'min', 'startOf'], [b, 'max', 'startOf']].map(function (v) { + const range = [[a, 'min', 'startOf'], [b, 'max', 'startOf']].map(function (v) { let val = v[0]; - let bound = v[1]; - let extend = v[2]; + const bound = v[1]; + const extend = v[2]; // grab a bound from the time filter if (val == null) { @@ -64,12 +64,12 @@ export default function IndexNameIntervalsService(timefilter) { if (!interval) throw new Error('Interval must be one of ' + _.pluck(intervals, 'name')); } - let indexList = []; + const indexList = []; let start = range.shift(); // turn stop into milliseconds to that it's not constantly converted by the while condition - let stop = range.shift().valueOf(); + const stop = range.shift().valueOf(); - let add = sortDirection === 'desc' ? 'unshift' : 'push'; + const add = sortDirection === 'desc' ? 'unshift' : 'push'; while (start <= stop) { const index = start.format(format); diff --git a/src/ui/public/index_patterns/_local_cache.js b/src/ui/public/index_patterns/_local_cache.js index 64ec26847600a..52a7079f581b2 100644 --- a/src/ui/public/index_patterns/_local_cache.js +++ b/src/ui/public/index_patterns/_local_cache.js @@ -4,17 +4,17 @@ import angular from 'angular'; export default function LocalCacheFactory() { function LocalCache(opts) { opts = opts || {}; - let _id = opts.id || function (o) { return '' + o; }; + const _id = opts.id || function (o) { return '' + o; }; let _cache = {}; this.get = function (obj) { - let id = _id(obj); + const id = _id(obj); return _cache[id] ? JSON.parse(_cache[id]) : null; }; this.set = function (obj, val) { - let id = _id(obj); - let clean = !_cache.hasOwnProperty(id); + const id = _id(obj); + const clean = !_cache.hasOwnProperty(id); _cache[id] = angular.toJson(val); return clean; }; @@ -25,7 +25,7 @@ export default function LocalCacheFactory() { return; } - let id = _id(obj); + const id = _id(obj); delete _cache[id]; }; } diff --git a/src/ui/public/index_patterns/_map_field.js b/src/ui/public/index_patterns/_map_field.js index b4d3a4aa42f78..08a8ca55c10cc 100644 --- a/src/ui/public/index_patterns/_map_field.js +++ b/src/ui/public/index_patterns/_map_field.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexPatternsCastMappingTypeProvider from 'ui/index_patterns/_cast_mapping_type'; export default function MapFieldFn(Private, config) { - let castMappingType = Private(IndexPatternsCastMappingTypeProvider); + const castMappingType = Private(IndexPatternsCastMappingTypeProvider); /** * Accepts a field object and its name, and tries to give it a mapping @@ -10,11 +10,11 @@ export default function MapFieldFn(Private, config) { * @return {Object} - the resulting field after overrides and tweaking */ return function mapField(field, name) { - let keys = Object.keys(field.mapping); + const keys = Object.keys(field.mapping); if (keys.length === 0 || (name[0] === '_') && !_.contains(config.get('metaFields'), name)) return; // Override the mapping, even if elasticsearch says otherwise - let mappingOverrides = { + const mappingOverrides = { _source: { type: '_source' }, _index: { type: 'string' }, _type: { type: 'string' }, @@ -29,7 +29,7 @@ export default function MapFieldFn(Private, config) { } }; - let mapping = _.cloneDeep(field.mapping[keys.shift()]); + const mapping = _.cloneDeep(field.mapping[keys.shift()]); if (!mapping.index || mapping.index === 'no') { // elasticsearch responds with false sometimes and 'no' others diff --git a/src/ui/public/index_patterns/_mapper.js b/src/ui/public/index_patterns/_mapper.js index b3a0d5b4584e2..20472a3981d55 100644 --- a/src/ui/public/index_patterns/_mapper.js +++ b/src/ui/public/index_patterns/_mapper.js @@ -8,20 +8,20 @@ import IndexPatternsPatternToWildcardProvider from 'ui/index_patterns/_pattern_t import IndexPatternsLocalCacheProvider from 'ui/index_patterns/_local_cache'; export default function MapperService(Private, Promise, es, config, kbnIndex) { - let enhanceFieldsWithCapabilities = Private(EnhanceFieldsWithCapabilitiesProvider); - let transformMappingIntoFields = Private(IndexPatternsTransformMappingIntoFieldsProvider); - let intervals = Private(IndexPatternsIntervalsProvider); - let patternToWildcard = Private(IndexPatternsPatternToWildcardProvider); + const enhanceFieldsWithCapabilities = Private(EnhanceFieldsWithCapabilitiesProvider); + const transformMappingIntoFields = Private(IndexPatternsTransformMappingIntoFieldsProvider); + const intervals = Private(IndexPatternsIntervalsProvider); + const patternToWildcard = Private(IndexPatternsPatternToWildcardProvider); - let LocalCache = Private(IndexPatternsLocalCacheProvider); + const LocalCache = Private(IndexPatternsLocalCacheProvider); function Mapper() { // Save a reference to mapper - let self = this; + const self = this; // proper-ish cache, keeps a clean copy of the object, only returns copies of it's copy - let fieldCache = self.cache = new LocalCache(); + const fieldCache = self.cache = new LocalCache(); /** * Gets an object containing all fields with their mappings @@ -31,9 +31,9 @@ export default function MapperService(Private, Promise, es, config, kbnIndex) { * @async */ self.getFieldsForIndexPattern = function (indexPattern, skipIndexPatternCache) { - let id = indexPattern.id; + const id = indexPattern.id; - let cache = fieldCache.get(id); + const cache = fieldCache.get(id); if (cache) return Promise.resolve(cache); if (!skipIndexPatternCache) { @@ -85,7 +85,7 @@ export default function MapperService(Private, Promise, es, config, kbnIndex) { }) .then(function (resp) { // let all = Object.keys(resp).sort(); - let all = _(resp) + const all = _(resp) .map(function (index, key) { if (index.aliases) { return [Object.keys(index.aliases), key]; @@ -98,8 +98,8 @@ export default function MapperService(Private, Promise, es, config, kbnIndex) { .uniq(true) .value(); - let matches = all.filter(function (existingIndex) { - let parsed = moment(existingIndex, indexPattern.id); + const matches = all.filter(function (existingIndex) { + const parsed = moment(existingIndex, indexPattern.id); return existingIndex === parsed.format(indexPattern.id); }); diff --git a/src/ui/public/index_patterns/_pattern_cache.js b/src/ui/public/index_patterns/_pattern_cache.js index e9f57f5188e0a..7062ddb44bfd4 100644 --- a/src/ui/public/index_patterns/_pattern_cache.js +++ b/src/ui/public/index_patterns/_pattern_cache.js @@ -1,9 +1,9 @@ import _ from 'lodash'; export default function PatternCache() { - let vals = {}; + const vals = {}; - let validId = function (id) { + const validId = function (id) { return typeof id !== 'object'; }; diff --git a/src/ui/public/index_patterns/_pattern_to_wildcard.js b/src/ui/public/index_patterns/_pattern_to_wildcard.js index 447af376c807d..0193241ac12ca 100644 --- a/src/ui/public/index_patterns/_pattern_to_wildcard.js +++ b/src/ui/public/index_patterns/_pattern_to_wildcard.js @@ -5,7 +5,7 @@ export default function PatternToWildcardFn() { let inPattern = false; for (let i = 0; i < format.length; i++) { - let ch = format.charAt(i); + const ch = format.charAt(i); switch (ch) { case '[': inPattern = false; diff --git a/src/ui/public/index_patterns/_transform_mapping_into_fields.js b/src/ui/public/index_patterns/_transform_mapping_into_fields.js index 24184ad2a607b..37ab710a86ba7 100644 --- a/src/ui/public/index_patterns/_transform_mapping_into_fields.js +++ b/src/ui/public/index_patterns/_transform_mapping_into_fields.js @@ -3,7 +3,7 @@ import IndexPatternsMapFieldProvider from 'ui/index_patterns/_map_field'; import { ConflictTracker } from 'ui/index_patterns/_conflict_tracker'; export default function transformMappingIntoFields(Private, kbnIndex, config) { - let mapField = Private(IndexPatternsMapFieldProvider); + const mapField = Private(IndexPatternsMapFieldProvider); /** * Convert the ES response into the simple map for fields to @@ -15,17 +15,17 @@ export default function transformMappingIntoFields(Private, kbnIndex, config) { * use-cases */ return function (response) { - let fields = {}; + const fields = {}; const conflictTracker = new ConflictTracker(); _.each(response, function (index, indexName) { if (indexName === kbnIndex) return; _.each(index.mappings, function (mappings) { _.each(mappings, function (field, name) { - let keys = Object.keys(field.mapping); + const keys = Object.keys(field.mapping); if (keys.length === 0 || (name[0] === '_') && !_.contains(config.get('metaFields'), name)) return; - let mapping = mapField(field, name); + const mapping = mapField(field, name); // track the name, type and index for every field encountered so that the source // of conflicts can be described later conflictTracker.trackField(name, mapping.type, indexName); @@ -46,7 +46,7 @@ export default function transformMappingIntoFields(Private, kbnIndex, config) { config.get('metaFields').forEach(function (meta) { if (fields[meta]) return; - let field = { mapping: {} }; + const field = { mapping: {} }; field.mapping[meta] = {}; fields[meta] = mapField(field, meta); }); diff --git a/src/ui/public/index_patterns/index_patterns.js b/src/ui/public/index_patterns/index_patterns.js index 18ea1b7c95cfd..0a366fb8c2e07 100644 --- a/src/ui/public/index_patterns/index_patterns.js +++ b/src/ui/public/index_patterns/index_patterns.js @@ -9,20 +9,20 @@ import IndexPatternsMapperProvider from 'ui/index_patterns/_mapper'; import IndexPatternsPatternToWildcardProvider from 'ui/index_patterns/_pattern_to_wildcard'; import RegistryFieldFormatsProvider from 'ui/registry/field_formats'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana/index_patterns'); +const module = uiModules.get('kibana/index_patterns'); function IndexPatternsProvider(es, Notifier, Private, Promise, kbnIndex) { - let self = this; + const self = this; - let IndexPattern = Private(IndexPatternsIndexPatternProvider); - let patternCache = Private(IndexPatternsPatternCacheProvider); + const IndexPattern = Private(IndexPatternsIndexPatternProvider); + const patternCache = Private(IndexPatternsPatternCacheProvider); - let notify = new Notifier({ location: 'IndexPatterns Service'}); + const notify = new Notifier({ location: 'IndexPatterns Service'}); self.get = function (id) { if (!id) return self.make(); - let cache = patternCache.get(id); + const cache = patternCache.get(id); return cache || patternCache.set(id, self.make(id)); }; diff --git a/src/ui/public/index_patterns/route_setup/load_default.js b/src/ui/public/index_patterns/route_setup/load_default.js index 270e163c06c92..d59b1efb498cd 100644 --- a/src/ui/public/index_patterns/route_setup/load_default.js +++ b/src/ui/public/index_patterns/route_setup/load_default.js @@ -4,26 +4,26 @@ import { NoDefaultIndexPattern, NoDefinedIndexPatterns } from 'ui/errors'; import GetIdsProvider from '../_get_ids'; import CourierDataSourceRootSearchSourceProvider from 'ui/courier/data_source/_root_search_source'; import uiRoutes from 'ui/routes'; -let notify = new Notifier({ +const notify = new Notifier({ location: 'Index Patterns' }); module.exports = function (opts) { opts = opts || {}; - let whenMissingRedirectTo = opts.whenMissingRedirectTo || null; + const whenMissingRedirectTo = opts.whenMissingRedirectTo || null; let defaultRequiredToasts = null; uiRoutes .addSetupWork(function loadDefaultIndexPattern(Private, Promise, $route, config, indexPatterns) { - let getIds = Private(GetIdsProvider); - let rootSearchSource = Private(CourierDataSourceRootSearchSourceProvider); - let route = _.get($route, 'current.$$route'); + const getIds = Private(GetIdsProvider); + const rootSearchSource = Private(CourierDataSourceRootSearchSourceProvider); + const route = _.get($route, 'current.$$route'); return getIds() .then(function (patterns) { let defaultId = config.get('defaultIndex'); let defined = !!defaultId; - let exists = _.contains(patterns, defaultId); + const exists = _.contains(patterns, defaultId); if (defined && !exists) { config.remove('defaultIndex'); @@ -48,7 +48,7 @@ module.exports = function (opts) { // failure function (err, kbnUrl) { - let hasDefault = !(err instanceof NoDefaultIndexPattern); + const hasDefault = !(err instanceof NoDefaultIndexPattern); if (hasDefault || !whenMissingRedirectTo) throw err; // rethrow kbnUrl.change(whenMissingRedirectTo); diff --git a/src/ui/public/indexed_array/__tests__/indexed_array.js b/src/ui/public/indexed_array/__tests__/indexed_array.js index 69820fbe8bba4..040bc29046a06 100644 --- a/src/ui/public/indexed_array/__tests__/indexed_array.js +++ b/src/ui/public/indexed_array/__tests__/indexed_array.js @@ -4,7 +4,7 @@ import expect from 'expect.js'; import IndexedArray from 'ui/indexed_array'; // this is generally a data-structure that IndexedArray is good for managing -let users = [ +const users = [ { name: 'John', id: 69, username: 'beast', group: 'admins' }, { name: 'Anon', id: 0, username: 'shhhh', group: 'secret' }, { name: 'Fern', id: 42, username: 'kitty', group: 'editor' }, @@ -43,7 +43,7 @@ describe('IndexedArray', function () { describe('Indexing', function () { it('provides the initial set', function () { - let reg = new IndexedArray({ + const reg = new IndexedArray({ initialSet: [1, 2, 3] }); @@ -55,7 +55,7 @@ describe('IndexedArray', function () { }); it('indexes the initial set', function () { - let reg = new IndexedArray({ + const reg = new IndexedArray({ index: ['username'], initialSet: users }); @@ -66,11 +66,11 @@ describe('IndexedArray', function () { it('updates indices after values are added', function () { // split up the user list, and add it in chunks - let firstUser = users.slice(0, 1).pop(); - let otherUsers = users.slice(1); + const firstUser = users.slice(0, 1).pop(); + const otherUsers = users.slice(1); // start off with all but the first - let reg = new IndexedArray({ + const reg = new IndexedArray({ group: ['group'], order: ['id'], initialSet: otherUsers @@ -86,7 +86,7 @@ describe('IndexedArray', function () { it('updates indices after values are removed', function () { // start off with all - let reg = new IndexedArray({ + const reg = new IndexedArray({ group: ['group'], order: ['id'], initialSet: users @@ -95,18 +95,18 @@ describe('IndexedArray', function () { // remove the last reg.pop(); - let expectedCount = users.length - 1; + const expectedCount = users.length - 1; // indexed lists should be updated expect(reg).to.have.length(expectedCount); - let sumOfGroups = _.reduce(reg.byGroup, function (note, group) { + const sumOfGroups = _.reduce(reg.byGroup, function (note, group) { return note + group.length; }, 0); expect(sumOfGroups).to.eql(expectedCount); }); it('removes items based on a predicate', function () { - let reg = new IndexedArray({ + const reg = new IndexedArray({ group: ['group'], order: ['id'], initialSet: users @@ -120,7 +120,7 @@ describe('IndexedArray', function () { }); it('updates indices after values are re-ordered', function () { - let rawUsers = users.slice(0); + const rawUsers = users.slice(0); // collect and shuffle the ids available let ids = []; @@ -128,18 +128,18 @@ describe('IndexedArray', function () { ids = _.shuffle(ids); // move something here - let toI = ids.shift(); + const toI = ids.shift(); // from here - let fromI = ids.shift(); + const fromI = ids.shift(); // do the move - let move = function (arr) { arr.splice(toI, 0, arr.splice(fromI, 1)[0]); }; + const move = function (arr) { arr.splice(toI, 0, arr.splice(fromI, 1)[0]); }; - let reg = new IndexedArray({ + const reg = new IndexedArray({ index: ['username'], initialSet: rawUsers }); - let index = reg.byUsername; + const index = reg.byUsername; move(reg); diff --git a/src/ui/public/indexed_array/__tests__/inflector.js b/src/ui/public/indexed_array/__tests__/inflector.js index 3fc45e1a9f974..e7628ecf159fc 100644 --- a/src/ui/public/indexed_array/__tests__/inflector.js +++ b/src/ui/public/indexed_array/__tests__/inflector.js @@ -3,13 +3,13 @@ import expect from 'expect.js'; describe('IndexedArray Inflector', function () { it('returns a function', function () { - let getter = inflector(); + const getter = inflector(); expect(getter).to.be.a('function'); }); describe('fn', function () { it('prepends a prefix', function () { - let inflect = inflector('my'); + const inflect = inflector('my'); expect(inflect('Family')).to.be('myFamily'); expect(inflect('family')).to.be('myFamily'); @@ -17,7 +17,7 @@ describe('IndexedArray Inflector', function () { }); it('adds both a prefix and suffix', function () { - let inflect = inflector('foo', 'Bar'); + const inflect = inflector('foo', 'Bar'); expect(inflect('box')).to.be('fooBoxBar'); expect(inflect('box.car.MAX')).to.be('fooBoxCarMaxBar'); @@ -25,19 +25,19 @@ describe('IndexedArray Inflector', function () { }); it('ignores prefix if it is already at the end of the inflected string', function () { - let inflect = inflector('foo', 'Bar'); + const inflect = inflector('foo', 'Bar'); expect(inflect('fooBox')).to.be('fooBoxBar'); expect(inflect('FooBox')).to.be('FooBoxBar'); }); it('ignores postfix if it is already at the end of the inflected string', function () { - let inflect = inflector('foo', 'Bar'); + const inflect = inflector('foo', 'Bar'); expect(inflect('bar')).to.be('fooBar'); expect(inflect('showBoxBar')).to.be('fooShowBoxBar'); }); it('works with "name"', function () { - let inflect = inflector('in', 'Order'); + const inflect = inflector('in', 'Order'); expect(inflect('name')).to.be('inNameOrder'); }); }); diff --git a/src/ui/public/indexed_array/indexed_array.js b/src/ui/public/indexed_array/indexed_array.js index 3c7f81fcb52db..3f3325e2d3f7b 100644 --- a/src/ui/public/indexed_array/indexed_array.js +++ b/src/ui/public/indexed_array/indexed_array.js @@ -2,12 +2,12 @@ import _ from 'lodash'; import inflector from 'ui/indexed_array/inflector'; -let pathGetter = _(_.get).rearg(1, 0).ary(2); -let inflectIndex = inflector('by'); -let inflectOrder = inflector('in', 'Order'); +const pathGetter = _(_.get).rearg(1, 0).ary(2); +const inflectIndex = inflector('by'); +const inflectOrder = inflector('in', 'Order'); -let CLEAR_CACHE = {}; -let OPT_NAMES = IndexedArray.OPT_NAMES = ['index', 'group', 'order', 'initialSet', 'immutable']; +const CLEAR_CACHE = {}; +const OPT_NAMES = IndexedArray.OPT_NAMES = ['index', 'group', 'order', 'initialSet', 'immutable']; /** * Generic extension of Array class, which will index (and reindex) the @@ -69,11 +69,11 @@ IndexedArray.prototype._setupIndices = function (props, inflect, op) { // shortcut for empty props if (!props || props.length === 0) return; - let self = this; + const self = this; return props.map(function (prop) { - let from = pathGetter.partial(prop).value(); - let to = inflect(prop); + const from = pathGetter.partial(prop).value(); + const to = inflect(prop); let cache; Object.defineProperty(self, to, { @@ -105,7 +105,7 @@ IndexedArray.prototype._setupIndices = function (props, inflect, op) { * @return {undefined} */ IndexedArray.prototype._clearIndices = function () { - let self = this; + const self = this; self._indexNames.forEach(function (name) { self[name] = CLEAR_CACHE; }); @@ -120,7 +120,7 @@ IndexedArray.prototype._clearIndices = function () { * @return {[type]} [description] */ 'pop push shift splice unshift reverse'.split(' ').forEach(function (method) { - let orig = Array.prototype[method]; + const orig = Array.prototype[method]; IndexedArray.prototype[method] = function (/* args... */) { // call the original method with this context @@ -141,7 +141,7 @@ IndexedArray.prototype._clearIndices = function () { * @return {array} - the removed data */ IndexedArray.prototype.remove = function (predicate, context) { - let out = _.remove(this, predicate, context); + const out = _.remove(this, predicate, context); _.remove(this.raw, predicate, context); this._clearIndices(); return out; diff --git a/src/ui/public/indexed_array/inflector.js b/src/ui/public/indexed_array/inflector.js index f879cbdf8965e..e2ef5eca31cda 100644 --- a/src/ui/public/indexed_array/inflector.js +++ b/src/ui/public/indexed_array/inflector.js @@ -8,7 +8,7 @@ function startsWith(str, test) { } function endsWith(str, test) { - let tooShort = str.length < test.length; + const tooShort = str.length < test.length; if (tooShort) return; return str.substr(str.length - test.length).toLowerCase() === test.toLowerCase(); diff --git a/src/ui/public/jquery/__tests__/find_test_subject.js b/src/ui/public/jquery/__tests__/find_test_subject.js index 7a70ec05bd2a1..8302712e78f68 100644 --- a/src/ui/public/jquery/__tests__/find_test_subject.js +++ b/src/ui/public/jquery/__tests__/find_test_subject.js @@ -7,42 +7,42 @@ function $make(subject) { describe('jQuery.findTestSubject', function () { it('finds all of the element with a subject', function () { - let $container = $('
'); - let $match = $make('subject').appendTo($container); - let $noMatch = $make('notSubject').appendTo($container); + const $container = $('
'); + const $match = $make('subject').appendTo($container); + const $noMatch = $make('notSubject').appendTo($container); - let $found = $container.findTestSubject('subject'); + const $found = $container.findTestSubject('subject'); expect($found.is($match)).to.be(true); expect($found.is($noMatch)).to.be(false); }); it('finds multiple elements with a subject', function () { - let $container = $('
'); - let $match = $make('subject').appendTo($container); - let $otherMatch = $make('subject').appendTo($container); + const $container = $('
'); + const $match = $make('subject').appendTo($container); + const $otherMatch = $make('subject').appendTo($container); - let $found = $container.findTestSubject('subject'); + const $found = $container.findTestSubject('subject'); expect($found.filter($match).size()).to.be(1); expect($found.filter($otherMatch).size()).to.be(1); }); it('finds all of the elements with either subject', function () { - let $container = $('
'); - let $match1 = $make('subject').appendTo($container); - let $match2 = $make('alsoSubject').appendTo($container); - let $noMatch = $make('notSubject').appendTo($container); + const $container = $('
'); + const $match1 = $make('subject').appendTo($container); + const $match2 = $make('alsoSubject').appendTo($container); + const $noMatch = $make('notSubject').appendTo($container); - let $found = $container.findTestSubject('subject', 'alsoSubject'); + const $found = $container.findTestSubject('subject', 'alsoSubject'); expect($found.filter($match1).size()).to.be(1); expect($found.filter($match2).size()).to.be(1); expect($found.filter($noMatch).size()).to.be(0); }); it('finds all of the elements with a decendant selector', function () { - let $container = $('
'); - let $parent = $make('foo name').appendTo($container); - let $bar = $make('bar othername').appendTo($parent); - let $baz = $make('baz third name').appendTo($parent); + const $container = $('
'); + const $parent = $make('foo name').appendTo($container); + const $bar = $make('bar othername').appendTo($parent); + const $baz = $make('baz third name').appendTo($parent); expect($container.findTestSubject('foo bar').is($bar)).to.be(true); expect($container.findTestSubject('foo bar').is($baz)).to.be(false); @@ -52,9 +52,9 @@ describe('jQuery.findTestSubject', function () { }); it('finds elements with compound subjects', function () { - let $container = $('
'); - let $bar = $make('button bar').appendTo($container); - let $baz = $make('button baz').appendTo($container); + const $container = $('
'); + const $bar = $make('button bar').appendTo($container); + const $baz = $make('button baz').appendTo($container); expect($container.findTestSubject('button&bar').is($bar)).to.be(true); expect($container.findTestSubject('button& bar').is($bar)).to.be(true); diff --git a/src/ui/public/jquery/find_test_subject.js b/src/ui/public/jquery/find_test_subject.js index 935bb67a14558..ecb85ea5944c9 100644 --- a/src/ui/public/jquery/find_test_subject.js +++ b/src/ui/public/jquery/find_test_subject.js @@ -45,7 +45,7 @@ module.exports = function bindToJquery($) { function findTestSubject(...subjectSelectors) { let $els = $(); - let $context = this; + const $context = this; subjectSelectors.forEach(function (selector) { $els = $els.add($context.find(testSubjSelector(selector))); diff --git a/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js b/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js index bdb9759052e0d..e6fba1fbac2e4 100644 --- a/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js +++ b/src/ui/public/kbn_top_nav/__tests__/kbn_top_nav_controller.js @@ -303,7 +303,7 @@ describe('KbnTopNavController', function () { expect(controller.menuItems).to.have.length(4); // check that the items were added - let matches = controller.menuItems.reduce((acc, item) => { + const matches = controller.menuItems.reduce((acc, item) => { if (item.key === 'green' || item.key === 'red') { acc[item.key] = item; } @@ -324,7 +324,7 @@ describe('KbnTopNavController', function () { expect(controller.menuItems).to.have.length(3); // check that the items were added - let match = controller.menuItems.filter((item) => { + const match = controller.menuItems.filter((item) => { return item.key === 'green'; }); expect(match[0]).to.have.property('run'); diff --git a/src/ui/public/listen/__tests__/listen.js b/src/ui/public/listen/__tests__/listen.js index a4dcae53d176d..5c0384291f4e9 100644 --- a/src/ui/public/listen/__tests__/listen.js +++ b/src/ui/public/listen/__tests__/listen.js @@ -22,8 +22,8 @@ describe('listen component', function () { }); it('binds to an event emitter', function () { - let emitter = new Events(); - let $scope = $rootScope.$new(); + const emitter = new Events(); + const $scope = $rootScope.$new(); function handler() {} $scope.$listen(emitter, 'hello', handler); @@ -33,8 +33,8 @@ describe('listen component', function () { }); it('binds to $scope, waiting for the destroy event', function () { - let emitter = new Events(); - let $scope = $rootScope.$new(); + const emitter = new Events(); + const $scope = $rootScope.$new(); sinon.stub($scope, '$on'); sinon.stub($rootScope, '$on'); @@ -45,14 +45,14 @@ describe('listen component', function () { expect($rootScope.$on).to.have.property('callCount', 0); expect($scope.$on).to.have.property('callCount', 1); - let call = $scope.$on.firstCall; + const call = $scope.$on.firstCall; expect(call.args[0]).to.be('$destroy'); expect(call.args[1]).to.be.a('function'); }); it('unbinds the event handler when $destroy is triggered', function () { - let emitter = new Events(); - let $scope = $rootScope.$new(); + const emitter = new Events(); + const $scope = $rootScope.$new(); sinon.stub($scope, '$on'); sinon.stub(emitter, 'off'); @@ -62,7 +62,7 @@ describe('listen component', function () { $scope.$listen(emitter, 'hello', handler); // get the unbinder that was registered to $scope - let unbinder = $scope.$on.firstCall.args[1]; + const unbinder = $scope.$on.firstCall.args[1]; // call the unbinder expect(emitter.off).to.have.property('callCount', 0); @@ -70,7 +70,7 @@ describe('listen component', function () { expect(emitter.off).to.have.property('callCount', 1); // check that the off args were as expected - let call = emitter.off.firstCall; + const call = emitter.off.firstCall; expect(call.args[0]).to.be('hello'); expect(call.args[1]).to.be(handler); }); diff --git a/src/ui/public/notify/__tests__/lib/_format_es_msg.js b/src/ui/public/notify/__tests__/lib/_format_es_msg.js index 5b89a909386bc..0fd73df79edc1 100644 --- a/src/ui/public/notify/__tests__/lib/_format_es_msg.js +++ b/src/ui/public/notify/__tests__/lib/_format_es_msg.js @@ -3,23 +3,23 @@ import expect from 'expect.js'; describe('formatESMsg', function () { it('should return undefined if passed a basic error', function () { - let err = new Error('This is a normal error'); + const err = new Error('This is a normal error'); - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.be(undefined); }); it('should return undefined if passed a string', function () { - let err = 'This is a error string'; + const err = 'This is a error string'; - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.be(undefined); }); it('should return the root_cause if passed an extended elasticsearch', function () { - let err = new Error('This is an elasticsearch error'); + const err = new Error('This is an elasticsearch error'); err.resp = { error : { root_cause : [ @@ -30,13 +30,13 @@ describe('formatESMsg', function () { } }; - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.equal('I am the detailed message'); }); it('should combine the reason messages if more than one is returned.', function () { - let err = new Error('This is an elasticsearch error'); + const err = new Error('This is an elasticsearch error'); err.resp = { error : { root_cause : [ @@ -50,7 +50,7 @@ describe('formatESMsg', function () { } }; - let actual = formatESMsg(err); + const actual = formatESMsg(err); expect(actual).to.equal('I am the detailed message 1\nI am the detailed message 2'); }); diff --git a/src/ui/public/notify/__tests__/lib/_format_msg.js b/src/ui/public/notify/__tests__/lib/_format_msg.js index 725fd6a518d73..a58f2fa4e2d72 100644 --- a/src/ui/public/notify/__tests__/lib/_format_msg.js +++ b/src/ui/public/notify/__tests__/lib/_format_msg.js @@ -3,26 +3,26 @@ import expect from 'expect.js'; describe('formatMsg', function () { it('should prepend the second argument to result', function () { - let actual = formatMsg('error message', 'unit_test'); + const actual = formatMsg('error message', 'unit_test'); expect(actual).to.equal('unit_test: error message'); }); it('should handle a simple string', function () { - let actual = formatMsg('error message'); + const actual = formatMsg('error message'); expect(actual).to.equal('error message'); }); it('should handle a simple Error object', function () { - let err = new Error('error message'); - let actual = formatMsg(err); + const err = new Error('error message'); + const actual = formatMsg(err); expect(actual).to.equal('error message'); }); it('should handle a simple Angular $http error object', function () { - let err = { + const err = { data: { statusCode: 403, error: 'Forbidden', @@ -32,13 +32,13 @@ describe('formatMsg', function () { config: {}, statusText: 'Forbidden' }; - let actual = formatMsg(err); + const actual = formatMsg(err); expect(actual).to.equal('Error 403 Forbidden: [security_exception] action [indices:data/read/mget] is unauthorized for user [user]'); }); it('should handle an extended elasticsearch error', function () { - let err = { + const err = { resp : { error : { root_cause : [ @@ -50,7 +50,7 @@ describe('formatMsg', function () { } }; - let actual = formatMsg(err); + const actual = formatMsg(err); expect(actual).to.equal('I am the detailed message'); }); diff --git a/src/ui/public/notify/__tests__/notifier.js b/src/ui/public/notify/__tests__/notifier.js index 223536d6bb635..95d4c3382d556 100644 --- a/src/ui/public/notify/__tests__/notifier.js +++ b/src/ui/public/notify/__tests__/notifier.js @@ -70,7 +70,7 @@ describe('Notifier', function () { }); it('sets timeRemaining and decrements', function () { - let notif = notify('error'); + const notif = notify('error'); expect(notif.timeRemaining).to.equal(300); $interval.flush(1000); @@ -78,8 +78,8 @@ describe('Notifier', function () { }); it('closes notification on lifetime expiry', function () { - let expectation = sinon.mock(); - let notif = notifier.error(message, expectation); + const expectation = sinon.mock(); + const notif = notifier.error(message, expectation); expectation.once(); expectation.withExactArgs('ignore'); @@ -90,7 +90,7 @@ describe('Notifier', function () { }); it('allows canceling of timer', function () { - let notif = notify('error'); + const notif = notify('error'); expect(notif.timerId).to.not.be(undefined); notif.cancelTimer(); @@ -99,7 +99,7 @@ describe('Notifier', function () { }); it('resets timer on addition to stack', function () { - let notif = notify('error'); + const notif = notify('error'); $interval.flush(100000); expect(notif.timeRemaining).to.equal(200); @@ -109,12 +109,12 @@ describe('Notifier', function () { }); it('allows reporting', function () { - let includesReport = _.includes(notify('error').actions, 'report'); + const includesReport = _.includes(notify('error').actions, 'report'); expect(includesReport).to.true; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('error').actions, 'accept'); + const includesAccept = _.includes(notify('error').actions, 'accept'); expect(includesAccept).to.true; }); @@ -156,12 +156,12 @@ describe('Notifier', function () { }); it('does not allow reporting', function () { - let includesReport = _.includes(notify('warning').actions, 'report'); + const includesReport = _.includes(notify('warning').actions, 'report'); expect(includesReport).to.false; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('warning').actions, 'accept'); + const includesAccept = _.includes(notify('warning').actions, 'accept'); expect(includesAccept).to.true; }); @@ -203,12 +203,12 @@ describe('Notifier', function () { }); it('does not allow reporting', function () { - let includesReport = _.includes(notify('info').actions, 'report'); + const includesReport = _.includes(notify('info').actions, 'report'); expect(includesReport).to.false; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('info').actions, 'accept'); + const includesAccept = _.includes(notify('info').actions, 'accept'); expect(includesAccept).to.true; }); @@ -387,12 +387,12 @@ describe('Notifier', function () { }); it('does not allow reporting', function () { - let includesReport = _.includes(notify('banner').actions, 'report'); + const includesReport = _.includes(notify('banner').actions, 'report'); expect(includesReport).to.false; }); it('allows accepting', function () { - let includesAccept = _.includes(notify('banner').actions, 'accept'); + const includesAccept = _.includes(notify('banner').actions, 'accept'); expect(includesAccept).to.true; }); @@ -422,13 +422,13 @@ describe('Notifier', function () { function testVersionInfo(fnName) { context('when version is configured', function () { it('adds version to notification', function () { - let notification = notify(fnName); + const notification = notify(fnName); expect(notification.info.version).to.equal(version); }); }); context('when build number is configured', function () { it('adds buildNum to notification', function () { - let notification = notify(fnName); + const notification = notify(fnName); expect(notification.info.buildNum).to.equal(buildNum); }); }); diff --git a/src/ui/public/notify/directives.js b/src/ui/public/notify/directives.js index cb91b664d5403..bbef11f7e2bfe 100644 --- a/src/ui/public/notify/directives.js +++ b/src/ui/public/notify/directives.js @@ -5,7 +5,7 @@ import 'ui/notify/notify.less'; import 'ui/filters/markdown'; import 'ui/directives/truncated'; -let notify = uiModules.get('kibana/notify'); +const notify = uiModules.get('kibana/notify'); notify.directive('kbnNotifications', function () { return { diff --git a/src/ui/public/notify/errors.js b/src/ui/public/notify/errors.js index 68a040466124f..85f4ed66c7d47 100644 --- a/src/ui/public/notify/errors.js +++ b/src/ui/public/notify/errors.js @@ -1,8 +1,8 @@ import _ from 'lodash'; -let errors = {}; +const errors = {}; -let canStack = (function () { - let err = new Error(); +const canStack = (function () { + const err = new Error(); return !!err.stack; }()); diff --git a/src/ui/public/notify/lib/_format_es_msg.js b/src/ui/public/notify/lib/_format_es_msg.js index ac8c6b043a625..d812a04ec6eed 100644 --- a/src/ui/public/notify/lib/_format_es_msg.js +++ b/src/ui/public/notify/lib/_format_es_msg.js @@ -6,11 +6,11 @@ import _ from 'lodash'; * @returns {string} */ export default function formatESMsg(err) { - let rootCause = _.get(err, 'resp.error.root_cause'); + const rootCause = _.get(err, 'resp.error.root_cause'); if (!rootCause) { return; //undefined } - let result = _.pluck(rootCause, 'reason').join('\n'); + const result = _.pluck(rootCause, 'reason').join('\n'); return result; }; diff --git a/src/ui/public/notify/lib/_format_msg.js b/src/ui/public/notify/lib/_format_msg.js index 448c4fa4b2c8c..c77b550b5d20a 100644 --- a/src/ui/public/notify/lib/_format_msg.js +++ b/src/ui/public/notify/lib/_format_msg.js @@ -1,6 +1,6 @@ import _ from 'lodash'; import formatESMsg from 'ui/notify/lib/_format_es_msg'; -let has = _.has; +const has = _.has; /** * Formats the error message from an error object, extended elasticsearch @@ -15,7 +15,7 @@ function formatMsg(err, from) { rtn += from + ': '; } - let esMsg = formatESMsg(err); + const esMsg = formatESMsg(err); if (typeof err === 'string') { rtn += err; diff --git a/src/ui/public/notify/notifier.js b/src/ui/public/notify/notifier.js index 04ff558f53283..7b6f322316afc 100644 --- a/src/ui/public/notify/notifier.js +++ b/src/ui/public/notify/notifier.js @@ -7,17 +7,17 @@ import fatalSplashScreen from 'ui/notify/partials/fatal_splash_screen.html'; import 'ui/render_directive'; /* eslint no-console: 0 */ -let notifs = []; -let version = metadata.version; -let buildNum = metadata.buildNum; -let consoleGroups = ('group' in window.console) && ('groupCollapsed' in window.console) && ('groupEnd' in window.console); +const notifs = []; +const version = metadata.version; +const buildNum = metadata.buildNum; +const consoleGroups = ('group' in window.console) && ('groupCollapsed' in window.console) && ('groupEnd' in window.console); -let log = _.bindKey(console, 'log'); +const log = _.bindKey(console, 'log'); // used to identify the first call to fatal, set to false there let firstFatal = true; -let fatalToastTemplate = (function lazyTemplate(tmpl) { +const fatalToastTemplate = (function lazyTemplate(tmpl) { let compiled; return function (vars) { return (compiled || (compiled = _.template(tmpl)))(vars); @@ -34,7 +34,7 @@ function now() { function closeNotif(notif, cb = _.noop, key) { return function () { // this === notif - let i = notifs.indexOf(notif); + const i = notifs.indexOf(notif); if (i !== -1) notifs.splice(i, 1); cancelTimer(notif); @@ -188,7 +188,7 @@ Notifier.prototype.add = add; Notifier.prototype.set = set; function formatInfo() { - let info = []; + const info = []; if (!_.isUndefined(version)) { info.push(`Version: ${version}`); @@ -213,7 +213,7 @@ function formatStack(err) { * Functionality to check that */ function Notifier(opts) { - let self = this; + const self = this; opts = opts || {}; // label type thing to say where notifications came from @@ -291,7 +291,7 @@ Notifier.prototype.lifecycle = createGroupLogger('lifecycle', { * @return {function} - the wrapped function */ Notifier.prototype.timed = function (name, fn) { - let self = this; + const self = this; if (typeof name === 'function') { fn = name; @@ -299,8 +299,8 @@ Notifier.prototype.timed = function (name, fn) { } return function WrappedNotifierFunction() { - let cntx = this; - let args = arguments; + const cntx = this; + const args = arguments; return self.event(name, function () { return fn.apply(cntx, args); @@ -336,7 +336,7 @@ Notifier.prototype._showFatal = function (err) { }); } - let html = fatalToastTemplate({ + const html = fatalToastTemplate({ info: formatInfo(), msg: formatMsg(err, this.from), stack: formatStack(err) @@ -576,7 +576,7 @@ if (log === _.noop) { Notifier.prototype.log = _.noop; } else { Notifier.prototype.log = function () { - let args = [].slice.apply(arguments); + const args = [].slice.apply(arguments); if (this.from) args.unshift(this.from + ':'); log.apply(null, args); }; @@ -585,15 +585,15 @@ if (log === _.noop) { // general functionality used by .event() and .lifecycle() function createGroupLogger(type, opts) { // Track the groups managed by this logger - let groups = window[type + 'Groups'] = {}; + const groups = window[type + 'Groups'] = {}; return function logger(name, success) { let status; // status of the timer let exec; // function to execute and wrap let ret; // return value - let complete = function (val) { logger(name, true); return val; }; - let failure = function (err) { logger(name, false); throw err; }; + const complete = function (val) { logger(name, true); return val; }; + const failure = function (err) { logger(name, false); throw err; }; if (typeof success === 'function' || success === void 0) { // start @@ -609,7 +609,7 @@ function createGroupLogger(type, opts) { } else { groups[name] = now() - (groups[name] || 0); - let time = ' in ' + groups[name].toFixed(2) + 'ms'; + const time = ' in ' + groups[name].toFixed(2) + 'ms'; // end if (success) { diff --git a/src/ui/public/notify/notify.js b/src/ui/public/notify/notify.js index bcfa025cfcdea..76af7d3be906b 100644 --- a/src/ui/public/notify/notify.js +++ b/src/ui/public/notify/notify.js @@ -6,8 +6,8 @@ import Notifier from 'ui/notify/notifier'; import 'ui/notify/directives'; import chrome from 'ui/chrome'; import { kbnIndex } from 'ui/metadata'; -let module = modules.get('kibana/notify'); -let rootNotifier = new Notifier(); +const module = modules.get('kibana/notify'); +const rootNotifier = new Notifier(); module.factory('createNotifier', function () { return function (opts) { diff --git a/src/ui/public/number_list/number_list.js b/src/ui/public/number_list/number_list.js index 9c18da1f3058f..03206d8d4cd01 100644 --- a/src/ui/public/number_list/number_list.js +++ b/src/ui/public/number_list/number_list.js @@ -13,7 +13,7 @@ uiModules controllerAs: 'numberListCntr', require: 'ngModel', controller: function ($scope, $attrs, $parse) { - let self = this; + const self = this; // Called from the pre-link function once we have the controllers self.init = function (modelCntr) { @@ -25,7 +25,7 @@ uiModules self.getUnitName = _.partial($parse($attrs.unit), $scope); - let defaultRange = self.range = parseRange('[0,Infinity)'); + const defaultRange = self.range = parseRange('[0,Infinity)'); $scope.$watch(function () { return $attrs.range; @@ -48,7 +48,7 @@ uiModules * @return {undefined} */ self.remove = function (index) { - let list = self.getList(); + const list = self.getList(); if (!list) return; list.splice(index, 1); @@ -59,7 +59,7 @@ uiModules * @return {undefined} */ self.add = function () { - let list = self.getList(); + const list = self.getList(); if (!list) return; list.push(_.last(list) + 1); diff --git a/src/ui/public/number_list/number_list_input.js b/src/ui/public/number_list/number_list_input.js index 7fbf1b935e02f..21fe02ddf259a 100644 --- a/src/ui/public/number_list/number_list_input.js +++ b/src/ui/public/number_list/number_list_input.js @@ -3,11 +3,11 @@ import _ from 'lodash'; import keyMap from 'ui/utils/key_map'; import uiModules from 'ui/modules'; -let INVALID = {}; // invalid flag -let FLOATABLE = /^[\d\.e\-\+]+$/i; +const INVALID = {}; // invalid flag +const FLOATABLE = /^[\d\.e\-\+]+$/i; -let VALIDATION_ERROR = 'numberListRangeAndOrder'; -let DIRECTIVE_ATTR = 'kbn-number-list-input'; +const VALIDATION_ERROR = 'numberListRangeAndOrder'; +const DIRECTIVE_ATTR = 'kbn-number-list-input'; uiModules .get('kibana') @@ -16,13 +16,13 @@ uiModules restrict: 'A', require: ['ngModel', '^kbnNumberList'], link: function ($scope, $el, attrs, controllers) { - let ngModelCntr = controllers[0]; - let numberListCntr = controllers[1]; + const ngModelCntr = controllers[0]; + const numberListCntr = controllers[1]; - let $setModel = $parse(attrs.ngModel).assign; - let $repeater = $el.closest('[ng-repeat]'); + const $setModel = $parse(attrs.ngModel).assign; + const $repeater = $el.closest('[ng-repeat]'); - let handlers = { + const handlers = { up: change(add, 1), 'shift-up': change(addTenth, 1), @@ -54,14 +54,14 @@ uiModules function go(dir) { return function () { - let $to = $get(dir); + const $to = $get(dir); if ($to.size()) $to.focus(); else return false; }; } function idKey(event) { - let id = []; + const id = []; if (event.ctrlKey) id.push('ctrl'); if (event.shiftKey) id.push('shift'); if (event.metaKey) id.push('meta'); @@ -93,11 +93,11 @@ uiModules function change(using, mod) { return function () { - let str = String(ngModelCntr.$viewValue); - let val = parse(str); + const str = String(ngModelCntr.$viewValue); + const val = parse(str); if (val === INVALID) return; - let next = using(mod, val, str); + const next = using(mod, val, str); if (next === INVALID) return; $el.val(next); @@ -106,7 +106,7 @@ uiModules } function onKeydown(event) { - let handler = handlers[idKey(event)]; + const handler = handlers[idKey(event)]; if (!handler) return; if (handler(event) !== false) { @@ -133,13 +133,13 @@ uiModules if (isNaN(num)) return INVALID; } - let range = numberListCntr.range; + const range = numberListCntr.range; if (!range.within(num)) return INVALID; if ($scope.$index > 0) { - let i = $scope.$index - 1; - let list = numberListCntr.getList(); - let prev = list[i]; + const i = $scope.$index - 1; + const list = numberListCntr.getList(); + const prev = list[i]; if (num <= prev) return INVALID; } @@ -155,14 +155,14 @@ uiModules } } ], function () { - let valid = parse(ngModelCntr.$viewValue) !== INVALID; + const valid = parse(ngModelCntr.$viewValue) !== INVALID; ngModelCntr.$setValidity(VALIDATION_ERROR, valid); }); function validate(then) { return function (input) { let value = parse(input); - let valid = value !== INVALID; + const valid = value !== INVALID; value = valid ? value : input; ngModelCntr.$setValidity(VALIDATION_ERROR, valid); then && then(input, value); diff --git a/src/ui/public/paginated_table/__tests__/index.js b/src/ui/public/paginated_table/__tests__/index.js index 945118d794a70..08057156b65a4 100644 --- a/src/ui/public/paginated_table/__tests__/index.js +++ b/src/ui/public/paginated_table/__tests__/index.js @@ -13,9 +13,9 @@ describe('paginated table', function () { let $scope; let $elScope; let $orderBy; - let defaultPerPage = 10; + const defaultPerPage = 10; - let makeData = function (colCount, rowCount) { + const makeData = function (colCount, rowCount) { let columns = []; let rows = []; @@ -29,7 +29,7 @@ describe('paginated table', function () { if (_.isNumber(rowCount)) { _.times(rowCount, function (col) { - let rowItems = []; + const rowItems = []; _.times(columns.length, function (row) { rowItems.push('item' + col + row); @@ -47,7 +47,7 @@ describe('paginated table', function () { }; }; - let renderTable = function (cols, rows, perPage, sort) { + const renderTable = function (cols, rows, perPage, sort) { $scope.cols = cols || []; $scope.rows = rows || []; $scope.perPage = perPage || defaultPerPage; @@ -68,23 +68,23 @@ describe('paginated table', function () { describe('rendering', function () { it('should not display without rows', function () { - let cols = [{ + const cols = [{ title: 'test1' }]; - let rows = []; + const rows = []; renderTable(cols, rows); expect($el.children().size()).to.be(0); }); it('should render columns and rows', function () { - let data = makeData(2, 2); - let cols = data.columns; - let rows = data.rows; + const data = makeData(2, 2); + const cols = data.columns; + const rows = data.rows; renderTable(cols, rows); expect($el.children().size()).to.be(1); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); // should pad rows expect(tableRows.size()).to.be(defaultPerPage); // should contain the row data @@ -96,13 +96,13 @@ describe('paginated table', function () { it('should paginate rows', function () { // note: paginate truncates pages, so don't make too many - let rowCount = _.random(16, 24); - let perPageCount = _.random(5, 8); - let data = makeData(3, rowCount); - let pageCount = Math.ceil(rowCount / perPageCount); + const rowCount = _.random(16, 24); + const perPageCount = _.random(5, 8); + const data = makeData(3, rowCount); + const pageCount = Math.ceil(rowCount / perPageCount); renderTable(data.columns, data.rows, perPageCount); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.size()).to.be(perPageCount); // add 2 for the first and last page links expect($el.find('paginate-controls a').size()).to.be(pageCount + 2); @@ -132,7 +132,7 @@ describe('paginated table', function () { // }); it('should not sort by default', function () { - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be(data.rows[0][0]); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be(data.rows[lastRowIndex][0]); }); @@ -142,7 +142,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(999); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); expect(tableRows.eq(0).find('td').eq(2).text()).to.be('zzzz'); @@ -155,7 +155,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); expect(tableRows.eq(0).find('td').eq(2).text()).to.be('zzzz'); @@ -165,7 +165,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(2).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(1).find('td').eq(1).text()).to.be('bbbb'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); @@ -175,7 +175,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1, 'desc'); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('zzzz'); expect(tableRows.eq(1).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(2).find('td').eq(1).text()).to.be('bbbb'); @@ -186,7 +186,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('aaaa'); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be('zzzz'); }); @@ -197,7 +197,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('zzzz'); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be('aaaa'); }); @@ -209,7 +209,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(0); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be(data.rows[0][0]); expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).to.be('aaaa'); }); @@ -223,7 +223,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('aaaa'); expect(tableRows.eq(lastRowIndex).find('td').eq(1).text()).to.be('zzzz'); }); @@ -233,15 +233,15 @@ describe('paginated table', function () { describe('sorting duplicate columns', function () { let data; let paginatedTable; - let colText = 'test row'; + const colText = 'test row'; beforeEach(function () { - let cols = [ + const cols = [ { title: colText }, { title: colText }, { title: colText } ]; - let rows = [ + const rows = [ ['bbbb', 'aaaa', 'zzzz'], ['cccc', 'cccc', 'aaaa'], ['zzzz', 'bbbb', 'bbbb'], @@ -254,7 +254,7 @@ describe('paginated table', function () { }); it('should have duplicate column titles', function () { - let columns = $el.find('thead th span'); + const columns = $el.find('thead th span'); columns.each(function () { expect($(this).text()).to.be(colText); }); @@ -265,7 +265,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(2); $scope.$digest(); - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('td').eq(0).text()).to.be('cccc'); expect(tableRows.eq(0).find('td').eq(1).text()).to.be('cccc'); expect(tableRows.eq(0).find('td').eq(2).text()).to.be('aaaa'); @@ -302,7 +302,7 @@ describe('paginated table', function () { paginatedTable.sortColumn(1); $scope.$digest(); - let sorters = $el.find('thead th i'); + const sorters = $el.find('thead th i'); expect(sorters.eq(0).hasClass('fa-sort')).to.be(true); expect(sorters.eq(1).hasClass('fa-sort')).to.be(false); expect(sorters.eq(2).hasClass('fa-sort')).to.be(true); @@ -333,7 +333,7 @@ describe('paginated table', function () { }); it('should append object markup', function () { - let tableRows = $el.find('tbody tr'); + const tableRows = $el.find('tbody tr'); expect(tableRows.eq(0).find('h1').size()).to.be(0); expect(tableRows.eq(1).find('h1').size()).to.be(1); expect(tableRows.eq(2).find('h1').size()).to.be(0); diff --git a/src/ui/public/parse_query/lib/from_user.js b/src/ui/public/parse_query/lib/from_user.js index 6aac1f93c0feb..85b1ac423364f 100644 --- a/src/ui/public/parse_query/lib/from_user.js +++ b/src/ui/public/parse_query/lib/from_user.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import DecorateQueryProvider from 'ui/courier/data_source/_decorate_query'; export default function GetQueryFromUser(es, Private) { - let decorateQuery = Private(DecorateQueryProvider); + const decorateQuery = Private(DecorateQueryProvider); /** * Take text from the user and make it into a query object @@ -13,7 +13,7 @@ export default function GetQueryFromUser(es, Private) { return decorateQuery({query_string: {query: text}}); } - let matchAll = getQueryStringQuery('*'); + const matchAll = getQueryStringQuery('*'); // If we get an empty object, treat it as a * if (_.isObject(text)) { diff --git a/src/ui/public/parse_query/parse_query.js b/src/ui/public/parse_query/parse_query.js index 148a2f962f796..8d1ea46ddf4a8 100644 --- a/src/ui/public/parse_query/parse_query.js +++ b/src/ui/public/parse_query/parse_query.js @@ -4,7 +4,7 @@ import uiModules from 'ui/modules'; uiModules .get('kibana') .directive('parseQuery', function (Private) { - let fromUser = Private(ParseQueryLibFromUserProvider); + const fromUser = Private(ParseQueryLibFromUserProvider); return { restrict: 'A', @@ -13,7 +13,7 @@ uiModules 'ngModel': '=' }, link: function ($scope, elem, attr, ngModel) { - let init = function () { + const init = function () { $scope.ngModel = fromUser($scope.ngModel); }; diff --git a/src/ui/public/pattern_checker/pattern_checker.js b/src/ui/public/pattern_checker/pattern_checker.js index 134bfce760f61..bec93a9471ce3 100644 --- a/src/ui/public/pattern_checker/pattern_checker.js +++ b/src/ui/public/pattern_checker/pattern_checker.js @@ -17,7 +17,7 @@ module.directive('patternChecker', function () { controller: function (Notifier, $scope, $timeout, $http) { let validationTimeout; - let notify = new Notifier({ + const notify = new Notifier({ location: 'Add Data' }); diff --git a/src/ui/public/persisted_log/__tests__/persisted_log.js b/src/ui/public/persisted_log/__tests__/persisted_log.js index 11115f087e6f8..eff9efa14870c 100644 --- a/src/ui/public/persisted_log/__tests__/persisted_log.js +++ b/src/ui/public/persisted_log/__tests__/persisted_log.js @@ -8,9 +8,9 @@ let storage; let config; let PersistedLog; -let historyName = 'testHistory'; -let historyLimit = 10; -let payload = [ +const historyName = 'testHistory'; +const historyLimit = 10; +const payload = [ { first: 'clark', last: 'kent' }, { first: 'peter', last: 'parker' }, { first: 'bruce', last: 'wayne' } @@ -41,7 +41,7 @@ describe('PersistedLog', function () { describe('expected API', function () { it('has expected methods', function () { - let log = new PersistedLog(historyName); + const log = new PersistedLog(historyName); expect(log.add).to.be.a('function'); expect(log.get).to.be.a('function'); @@ -50,17 +50,17 @@ describe('PersistedLog', function () { describe('internal functionality', function () { it('reads from storage', function () { - let log = new PersistedLog(historyName); + const log = new PersistedLog(historyName); expect(storage.get.calledOnce).to.be(true); expect(storage.get.calledWith(historyName)).to.be(true); }); it('writes to storage', function () { - let log = new PersistedLog(historyName); - let newItem = { first: 'diana', last: 'prince' }; + const log = new PersistedLog(historyName); + const newItem = { first: 'diana', last: 'prince' }; - let data = log.add(newItem); + const data = log.add(newItem); expect(storage.set.calledOnce).to.be(true); expect(data).to.eql([newItem]); @@ -70,19 +70,19 @@ describe('PersistedLog', function () { describe('persisting data', function () { it('fetches records from storage', function () { storage.get.returns(payload); - let log = new PersistedLog(historyName); + const log = new PersistedLog(historyName); - let items = log.get(); + const items = log.get(); expect(items.length).to.equal(3); expect(items).to.eql(payload); }); it('prepends new records', function () { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName); - let newItem = { first: 'selina', last: 'kyle' }; + const log = new PersistedLog(historyName); + const newItem = { first: 'selina', last: 'kyle' }; - let items = log.add(newItem); + const items = log.add(newItem); expect(items.length).to.equal(payload.length + 1); expect(items[0]).to.eql(newItem); }); @@ -90,40 +90,40 @@ describe('PersistedLog', function () { describe('stack options', function () { it('should observe the maxLength option', function () { - let bulkData = []; + const bulkData = []; for (let i = 0; i < historyLimit; i++) { bulkData.push(['record ' + i]); } storage.get.returns(bulkData); - let log = new PersistedLog(historyName, { maxLength: historyLimit }); + const log = new PersistedLog(historyName, { maxLength: historyLimit }); log.add(['new array 1']); - let items = log.add(['new array 2']); + const items = log.add(['new array 2']); expect(items.length).to.equal(historyLimit); }); it('should observe the filterDuplicates option', function () { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName, { filterDuplicates: true }); - let newItem = payload[1]; + const log = new PersistedLog(historyName, { filterDuplicates: true }); + const newItem = payload[1]; - let items = log.add(newItem); + const items = log.add(newItem); expect(items.length).to.equal(payload.length); }); it ('should truncate the list upon initialization if too long', () => { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName, {maxLength: 1}); - let items = log.get(); + const log = new PersistedLog(historyName, {maxLength: 1}); + const items = log.get(); expect(items.length).to.equal(1); }); it('should allow a maxLength of 0', () => { storage.get.returns(payload.slice(0)); - let log = new PersistedLog(historyName, {maxLength: 0}); - let items = log.get(); + const log = new PersistedLog(historyName, {maxLength: 0}); + const items = log.get(); expect(items.length).to.equal(0); }); }); diff --git a/src/ui/public/persisted_state/__tests__/persisted_state.js b/src/ui/public/persisted_state/__tests__/persisted_state.js index af6a2deb3c9cf..e988bbf473aa7 100644 --- a/src/ui/public/persisted_state/__tests__/persisted_state.js +++ b/src/ui/public/persisted_state/__tests__/persisted_state.js @@ -36,7 +36,7 @@ describe('Persisted State', function () { }); it('should create a state instance with data', function () { - let val = { red: 'blue' }; + const val = { red: 'blue' }; persistedState = new PersistedState(val); expect(persistedState.get()).to.eql(val); @@ -45,7 +45,7 @@ describe('Persisted State', function () { }); it('should create a copy of the state passed in', function () { - let val = { red: 'blue' }; + const val = { red: 'blue' }; persistedState = new PersistedState(val); expect(persistedState.get()).to.eql(val); @@ -53,10 +53,10 @@ describe('Persisted State', function () { }); it('should not throw if creating valid child object', function () { - let run = function () { - let val = { red: 'blue' }; - let path = ['test.path']; - let parent = new PersistedState(); + const run = function () { + const val = { red: 'blue' }; + const path = ['test.path']; + const parent = new PersistedState(); new PersistedState(val, path, parent); }; @@ -64,8 +64,8 @@ describe('Persisted State', function () { }); it('should throw if given an invalid value', function () { - let run = function () { - let val = 'bananas'; + const run = function () { + const val = 'bananas'; new PersistedState(val); }; @@ -75,10 +75,10 @@ describe('Persisted State', function () { }); it('should not throw if given primitive to child', function () { - let run = function () { - let val = 'bananas'; - let path = ['test.path']; - let parent = new PersistedState(); + const run = function () { + const val = 'bananas'; + const path = ['test.path']; + const parent = new PersistedState(); new PersistedState(val, path, parent); }; @@ -86,10 +86,10 @@ describe('Persisted State', function () { }); it('should throw if given an invalid parent object', function () { - let run = function () { - let val = { red: 'blue' }; - let path = ['test.path']; - let parent = {}; + const run = function () { + const val = { red: 'blue' }; + const path = ['test.path']; + const parent = {}; new PersistedState(val, path, parent); }; @@ -99,10 +99,10 @@ describe('Persisted State', function () { }); it('should throw if given a parent without a path', function () { - let run = function () { - let val = { red: 'blue' }; + const run = function () { + const val = { red: 'blue' }; let path; - let parent = new PersistedState(); + const parent = new PersistedState(); new PersistedState(val, path, parent); }; @@ -117,8 +117,8 @@ describe('Persisted State', function () { let childState; it('should not append the child state to the parent, without parent value', function () { - let childIndex = 'i can haz child'; - let persistedState = new PersistedState(); + const childIndex = 'i can haz child'; + const persistedState = new PersistedState(); childState = persistedState.createChild(childIndex); // parent state should not contain the child state @@ -127,9 +127,9 @@ describe('Persisted State', function () { }); it('should not append the child state to the parent, with parent value', function () { - let childIndex = 'i can haz child'; - let persistedStateValue = { original: true }; - let persistedState = new PersistedState(persistedStateValue); + const childIndex = 'i can haz child'; + const persistedStateValue = { original: true }; + const persistedState = new PersistedState(persistedStateValue); childState = persistedState.createChild(childIndex); // child state should be empty, we didn't give it any default data @@ -141,14 +141,14 @@ describe('Persisted State', function () { }); it('should append the child state to the parent, with parent and child values', function () { - let childIndex = 'i can haz child'; - let childStateValue = { tacos: 'yes please' }; - let persistedStateValue = { original: true }; - let persistedState = new PersistedState(persistedStateValue); + const childIndex = 'i can haz child'; + const childStateValue = { tacos: 'yes please' }; + const persistedStateValue = { original: true }; + const persistedState = new PersistedState(persistedStateValue); childState = persistedState.createChild(childIndex, childStateValue); // parent state should contain the child and its original state value - let parentState = persistedState.get(); + const parentState = persistedState.get(); expect(parentState).to.have.property('original', true); expect(parentState).to.have.property(childIndex); expect(parentState[childIndex]).to.eql(childStateValue); @@ -157,15 +157,15 @@ describe('Persisted State', function () { describe('deep child state creation', function () { it('should delegate get/set calls to parent state', function () { - let children = [{ + const children = [{ path: 'first*child', value: { first: true, second: false } }, { path: 'second child', value: { first: false, second: true } }]; - let persistedStateValue = { original: true }; - let persistedState = new PersistedState(persistedStateValue); + const persistedStateValue = { original: true }; + const persistedState = new PersistedState(persistedStateValue); // first child is a child of the parent persistedState children[0].instance = persistedState.createChild(children[0].path, children[0].value); @@ -176,7 +176,7 @@ describe('Persisted State', function () { expect(children[1].instance.get()).to.eql(children[1].value); // parent should contain original props and first child path, but not the second child path - let parentState = persistedState.get(); + const parentState = persistedState.get(); _.keys(persistedStateValue).forEach(function (key) { expect(parentState).to.have.property(key); }); @@ -184,28 +184,28 @@ describe('Persisted State', function () { expect(parentState).to.not.have.property(children[1].path); // second child path should be inside the first child - let firstChildState = children[0].instance.get(); + const firstChildState = children[0].instance.get(); expect(firstChildState).to.have.property(children[1].path); expect(firstChildState[children[1].path]).to.eql(children[1].value); // check that the second child is still accessible from the parent instance - let firstChild = persistedState.get(children[0].path); + const firstChild = persistedState.get(children[0].path); expect(firstChild).to.have.property(children[1].path); }); }); describe('child state removal', function () { it('should clear path from parent state', function () { - let persistedState = new PersistedState(); - let childState = persistedState.createChild('child', { userId: 1234 }); + const persistedState = new PersistedState(); + const childState = persistedState.createChild('child', { userId: 1234 }); expect(persistedState.get()).to.eql({ child: { userId: 1234 }}); persistedState.removeChild('child'); expect(persistedState.get()).to.eql({}); }); it('should reset original parent value at path', function () { - let persistedState = new PersistedState({ user: 1234 }); - let childState = persistedState.createChild('user', { id: 5678 }); + const persistedState = new PersistedState({ user: 1234 }); + const childState = persistedState.createChild('user', { id: 5678 }); expect(persistedState.get()).to.eql({ user: { id: 5678 }}); persistedState.removeChild('user'); @@ -213,8 +213,8 @@ describe('Persisted State', function () { }); it('should clear changedState', function () { - let persistedState = new PersistedState({ user: 1234 }); - let childState = persistedState.createChild('user'); + const persistedState = new PersistedState({ user: 1234 }); + const childState = persistedState.createChild('user'); childState.set('name', 'user name'); expect(persistedState.getChanges()).to.eql({ user: { name: 'user name' }}); @@ -225,16 +225,16 @@ describe('Persisted State', function () { describe('deep child state removal', function () { it('should clear path from parent state', function () { - let persistedState = new PersistedState(); - let childState = persistedState.createChild('child.state', { userId: 1234 }); + const persistedState = new PersistedState(); + const childState = persistedState.createChild('child.state', { userId: 1234 }); expect(persistedState.get()).to.eql({ child: { state: { userId: 1234 }}}); persistedState.removeChild('child.state'); expect(persistedState.get()).to.eql({}); }); it('should reset original parent value at path', function () { - let persistedState = new PersistedState({ user: { id: 1234 }}); - let childState = persistedState.createChild('user.id', 5678); + const persistedState = new PersistedState({ user: { id: 1234 }}); + const childState = persistedState.createChild('user.id', 5678); expect(persistedState.get()).to.eql({ user: { id: 5678 }}); persistedState.removeChild('user.id'); @@ -242,8 +242,8 @@ describe('Persisted State', function () { }); it('should reset original parent other values at path', function () { - let persistedState = new PersistedState({ user: { name: 'user' }}); - let childState = persistedState.createChild('user.id', 5678); + const persistedState = new PersistedState({ user: { name: 'user' }}); + const childState = persistedState.createChild('user.id', 5678); expect(persistedState.get()).to.eql({ user: { name: 'user', id: 5678 }}); persistedState.removeChild('user.id'); @@ -251,8 +251,8 @@ describe('Persisted State', function () { }); it('should clear the changed state', function () { - let persistedState = new PersistedState({ user: { id: 1234 }}); - let childState = persistedState.createChild('user.name'); + const persistedState = new PersistedState({ user: { id: 1234 }}); + const childState = persistedState.createChild('user.name'); childState.set('user name'); expect(persistedState.getChanges()).to.eql({ user: { name: 'user name' }}); @@ -264,8 +264,8 @@ describe('Persisted State', function () { describe('child state conditions', function () { it('should be merged with the parent state', function () { - let parent = new PersistedState({ name: 'test' }); - let child = parent.createChild('child', 'value'); + const parent = new PersistedState({ name: 'test' }); + const child = parent.createChild('child', 'value'); expect(parent.get()).to.eql({ name: 'test', child: 'value' @@ -285,8 +285,8 @@ describe('Persisted State', function () { }); it('should give child state precedence', function () { - let parent = new PersistedState({ user: { id: 1234, name: 'test' }}); - let child = parent.createChild('user', { name: 'child test' }); + const parent = new PersistedState({ user: { id: 1234, name: 'test' }}); + const child = parent.createChild('user', { name: 'child test' }); expect(parent.get()).to.eql({ user: { id: 1234, @@ -299,8 +299,8 @@ describe('Persisted State', function () { }); it('should be cleaned up with removeChild', function () { - let parent = new PersistedState({ name: 'test' }); - let child = parent.createChild('child', 'value'); + const parent = new PersistedState({ name: 'test' }); + const child = parent.createChild('child', 'value'); expect(parent.get()).to.eql({ name: 'test', child: 'value' @@ -315,16 +315,16 @@ describe('Persisted State', function () { describe('colliding child paths and parent state values', function () { it('should not change the child path value by default', function () { - let childIndex = 'childTest'; - let persistedStateValue = {}; + const childIndex = 'childTest'; + const persistedStateValue = {}; persistedStateValue[childIndex] = { overlapping_index: true }; - let persistedState = new PersistedState(persistedStateValue); + const persistedState = new PersistedState(persistedStateValue); let state = persistedState.get(); expect(state).to.have.property(childIndex); expect(state[childIndex]).to.eql(persistedStateValue[childIndex]); - let childState = persistedState.createChild(childIndex); + const childState = persistedState.createChild(childIndex); expect(childState.get()).to.eql(persistedStateValue[childIndex]); // make sure the parent state is still the same @@ -334,21 +334,21 @@ describe('Persisted State', function () { }); it('should merge default child state', function () { - let childIndex = 'childTest'; - let childStateValue = { child_index: false }; - let persistedStateValue = {}; + const childIndex = 'childTest'; + const childStateValue = { child_index: false }; + const persistedStateValue = {}; persistedStateValue[childIndex] = { parent_index: true }; - let persistedState = new PersistedState(persistedStateValue); + const persistedState = new PersistedState(persistedStateValue); let state = persistedState.get(); expect(state).to.have.property(childIndex); expect(state[childIndex]).to.eql(persistedStateValue[childIndex]); // pass in child state value - let childState = persistedState.createChild(childIndex, childStateValue); + const childState = persistedState.createChild(childIndex, childStateValue); // parent's default state is merged with child state - let compare = _.merge({}, childStateValue, persistedStateValue[childIndex]); + const compare = _.merge({}, childStateValue, persistedStateValue[childIndex]); expect(childState.get()).to.eql(compare); state = persistedState.get(); expect(state).to.have.property(childIndex); @@ -358,11 +358,11 @@ describe('Persisted State', function () { describe('mutation', function () { it('should not mutate the internal object', function () { - let persistedStateValue = { hello: 'world' }; - let insertedObj = { farewell: 'cruel world' }; - let persistedState = new PersistedState(persistedStateValue); + const persistedStateValue = { hello: 'world' }; + const insertedObj = { farewell: 'cruel world' }; + const persistedState = new PersistedState(persistedStateValue); - let obj = persistedState.get(); + const obj = persistedState.get(); _.assign(obj, insertedObj); expect(obj).to.have.property('farewell'); @@ -379,38 +379,38 @@ describe('Persisted State', function () { describe('exporting state to JSON', function () { it('should return the full JSON representation', function () { - let persistedState = new PersistedState(persistedStateValue); + const persistedState = new PersistedState(persistedStateValue); - let json = persistedState.toJSON(); + const json = persistedState.toJSON(); expect(json).to.eql(persistedStateValue); }); it('should return the JSON representation of the child state', function () { - let persistedState = new PersistedState(persistedStateValue); - let childState = persistedState.createChild('awesome', { pants: false }); + const persistedState = new PersistedState(persistedStateValue); + const childState = persistedState.createChild('awesome', { pants: false }); expect(childState.toJSON()).to.eql({ pants: false }); // verify JSON output of the parent state - let parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); + const parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); expect(persistedState.toJSON()).to.eql(parentCompare); }); it('should export stringified version of state', function () { - let persistedState = new PersistedState(persistedStateValue); - let childState = persistedState.createChild('awesome', { pants: false }); + const persistedState = new PersistedState(persistedStateValue); + const childState = persistedState.createChild('awesome', { pants: false }); - let data = childState.toString(); + const data = childState.toString(); expect(JSON.parse(data)).to.eql({ pants: false }); // verify JSON output of the parent state - let parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); + const parentCompare = _.assign({ awesome: { pants: false }}, persistedStateValue); expect(JSON.parse(persistedState.toString())).to.eql(parentCompare); }); }); describe('importing state from JSON string (hydration)', function () { it('should set the state from JSON string input', function () { - let stateJSON = JSON.stringify(persistedStateValue); - let persistedState = new PersistedState(); + const stateJSON = JSON.stringify(persistedStateValue); + const persistedState = new PersistedState(); expect(persistedState.get()).to.eql({}); persistedState.fromString(stateJSON); @@ -421,7 +421,7 @@ describe('Persisted State', function () { describe('get state', function () { it('should perform deep gets with various formats', function () { - let obj = { + const obj = { red: { green: { blue: 'yellow' @@ -432,7 +432,7 @@ describe('Persisted State', function () { violet: '' } }; - let persistedState = new PersistedState(obj); + const persistedState = new PersistedState(obj); expect(persistedState.get()).to.eql(obj); expect(persistedState.get('red')).to.eql({ green: { blue: 'yellow' } }); @@ -451,7 +451,7 @@ describe('Persisted State', function () { }); it('should perform deep gets with arrays', function () { - let persistedState = new PersistedState({ hello: { nouns: ['world', 'humans', 'everyone'] } }); + const persistedState = new PersistedState({ hello: { nouns: ['world', 'humans', 'everyone'] } }); expect(persistedState.get()).to.eql({ hello: { nouns: ['world', 'humans', 'everyone'] } }); expect(persistedState.get('hello')).to.eql({ nouns: ['world', 'humans', 'everyone'] }); @@ -459,9 +459,9 @@ describe('Persisted State', function () { }); it('should pass defaults to parent delegation', function () { - let persistedState = new PersistedState({ parent: true }); - let childState = persistedState.createChild('child', { account: { name: 'first child' }}); - let defaultValue = 'i have no data'; + const persistedState = new PersistedState({ parent: true }); + const childState = persistedState.createChild('child', { account: { name: 'first child' }}); + const defaultValue = 'i have no data'; expect(childState.get('account.name', defaultValue)).to.eql('first child'); expect(childState.get('account.age', defaultValue)).to.eql(defaultValue); @@ -471,25 +471,25 @@ describe('Persisted State', function () { describe('set state', function () { describe('path format support', function () { it('should create deep objects from dot notation', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); persistedState.set('one.two.three', 4); expect(persistedState.get()).to.eql({ one: { two: { three: 4 } } }); }); it('should create deep objects from array notation', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); persistedState.set('one[two][three]', 4); expect(persistedState.get()).to.eql({ one: { two: { three: 4 } } }); }); it('should create deep objects from arrays', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); persistedState.set(['one', 'two', 'three'], 4); expect(persistedState.get()).to.eql({ one: { two: { three: 4 } } }); }); it('should create deep objects with an existing path', function () { - let persistedState = new PersistedState({}, 'deep.path'); + const persistedState = new PersistedState({}, 'deep.path'); persistedState.set('green[red].blue', 4); expect(persistedState.get()).to.eql({ green: { red: { blue: 4 } }}); }); @@ -555,19 +555,19 @@ describe('Persisted State', function () { describe('internal state tracking', function () { it('should be an empty object', function () { - let persistedState = new PersistedState(); + const persistedState = new PersistedState(); expect(persistedState._defaultState).to.eql({}); }); it('should store the default state value', function () { - let val = { one: 1, two: 2 }; - let persistedState = new PersistedState(val); + const val = { one: 1, two: 2 }; + const persistedState = new PersistedState(val); expect(persistedState._defaultState).to.eql(val); }); it('should keep track of changes', function () { - let val = { one: 1, two: 2 }; - let persistedState = new PersistedState(val); + const val = { one: 1, two: 2 }; + const persistedState = new PersistedState(val); persistedState.set('two', 22); expect(persistedState._defaultState).to.eql(val); @@ -579,14 +579,14 @@ describe('Persisted State', function () { let persistedState; let emitter; - let getByType = function (type, spy) { + const getByType = function (type, spy) { spy = spy || emitter; return spy.getCalls().filter(function (call) { return call.args[0] === type; }); }; - let watchEmitter = function (state) { + const watchEmitter = function (state) { return sinon.spy(state, 'emit'); }; @@ -667,7 +667,7 @@ describe('Persisted State', function () { }); it('should emit on parent and child instances', function (done) { - let child = persistedState.createChild('checker'); + const child = persistedState.createChild('checker'); expect(getByType('change')).to.have.length(0); // parent and child should emit, set up listener to test diff --git a/src/ui/public/persisted_state/persisted_state.js b/src/ui/public/persisted_state/persisted_state.js index d883732fb3a08..2ff9d38989d3f 100644 --- a/src/ui/public/persisted_state/persisted_state.js +++ b/src/ui/public/persisted_state/persisted_state.js @@ -11,7 +11,7 @@ import SimpleEmitter from 'ui/utils/simple_emitter'; import EventsProvider from 'ui/events'; export default function (Private) { - let Events = Private(EventsProvider); + const Events = Private(EventsProvider); function validateParent(parent, path) { if (path.length <= 0) { @@ -23,7 +23,7 @@ export default function (Private) { } function validateValue(value) { - let msg = 'State value must be a plain object'; + const msg = 'State value must be a plain object'; if (!value) return; if (!_.isPlainObject(value)) throw new errors.PersistedStateError(msg); } @@ -79,21 +79,21 @@ export default function (Private) { }; PersistedState.prototype.set = function (key, value) { - let params = prepSetParams(key, value, this._path); - let val = this._set(params.key, params.value); + const params = prepSetParams(key, value, this._path); + const val = this._set(params.key, params.value); this.emit('set'); return val; }; PersistedState.prototype.setSilent = function (key, value) { - let params = prepSetParams(key, value, this._path); + const params = prepSetParams(key, value, this._path); return this._set(params.key, params.value, true); }; PersistedState.prototype.reset = function (path) { - let keyPath = this._getIndex(path); - let origValue = _.get(this._defaultState, keyPath); - let currentValue = _.get(this._mergedState, keyPath); + const keyPath = this._getIndex(path); + const origValue = _.get(this._defaultState, keyPath); + const currentValue = _.get(this._mergedState, keyPath); if (_.isUndefined(origValue)) { this._cleanPath(path, this._mergedState); @@ -114,7 +114,7 @@ export default function (Private) { }; PersistedState.prototype.removeChild = function (path) { - let origValue = _.get(this._defaultState, this._getIndex(path)); + const origValue = _.get(this._defaultState, this._getIndex(path)); if (_.isUndefined(origValue)) { this.reset(path); @@ -145,19 +145,19 @@ export default function (Private) { }; PersistedState.prototype._getPartialIndex = function (key) { - let keyPath = this._getIndex(key); + const keyPath = this._getIndex(key); return keyPath.slice(this._path.length); }; PersistedState.prototype._cleanPath = function (path, stateTree) { - let partialPath = this._getPartialIndex(path); + const partialPath = this._getPartialIndex(path); let remove = true; // recursively delete value tree, when no other keys exist while (partialPath.length > 0) { - let lastKey = partialPath.splice(partialPath.length - 1, 1)[0]; - let statePath = this._path.concat(partialPath); - let stateVal = statePath.length > 0 ? _.get(stateTree, statePath) : stateTree; + const lastKey = partialPath.splice(partialPath.length - 1, 1)[0]; + const statePath = this._path.concat(partialPath); + const stateVal = statePath.length > 0 ? _.get(stateTree, statePath) : stateTree; // if stateVal isn't an object, do nothing if (!_.isPlainObject(stateVal)) return; @@ -168,13 +168,13 @@ export default function (Private) { }; PersistedState.prototype._getDefault = function () { - let def = (this._hasPath()) ? undefined : {}; + const def = (this._hasPath()) ? undefined : {}; return (this._parent ? this.get() : def); }; PersistedState.prototype._setPath = function (path) { - let isString = _.isString(path); - let isArray = _.isArray(path); + const isString = _.isString(path); + const isArray = _.isArray(path); if (!isString && !isArray) return []; return (isString) ? [this._getIndex(path)] : path; @@ -202,11 +202,11 @@ export default function (Private) { }; PersistedState.prototype._set = function (key, value, silent, initialChildState) { - let self = this; + const self = this; let stateChanged = false; - let initialState = !this._initialized; - let keyPath = this._getIndex(key); - let hasKeyPath = keyPath.length > 0; + const initialState = !this._initialized; + const keyPath = this._getIndex(key); + const hasKeyPath = keyPath.length > 0; // if this is the initial state value, save value as the default if (initialState) { @@ -232,7 +232,7 @@ export default function (Private) { } } else { // check for changes at path, emit an event when different - let curVal = hasKeyPath ? this.get(keyPath) : this._mergedState; + const curVal = hasKeyPath ? this.get(keyPath) : this._mergedState; stateChanged = !_.isEqual(curVal, value); if (!initialChildState) { @@ -249,11 +249,11 @@ export default function (Private) { } // update the merged state value - let targetObj = this._mergedState || _.cloneDeep(this._defaultState); - let sourceObj = _.merge({}, this._defaultChildState, this._changedState); + const targetObj = this._mergedState || _.cloneDeep(this._defaultState); + const sourceObj = _.merge({}, this._defaultChildState, this._changedState); // handler arguments are (targetValue, sourceValue, key, target, source) - let mergeMethod = function (targetValue, sourceValue, mergeKey) { + const mergeMethod = function (targetValue, sourceValue, mergeKey) { // if not initial state, skip default merge method (ie. return value, see note below) if (!initialState && !initialChildState && _.isEqual(keyPath, self._getIndex(mergeKey))) { // use the sourceValue or fall back to targetValue diff --git a/src/ui/public/private/__tests__/private.js b/src/ui/public/private/__tests__/private.js index fc3dab39d3436..0efb5ac1fc110 100644 --- a/src/ui/public/private/__tests__/private.js +++ b/src/ui/public/private/__tests__/private.js @@ -11,12 +11,12 @@ describe('Private module loader', function () { })); it('accepts a provider that will be called to init a module', function () { - let football = {}; + const football = {}; function Provider() { return football; } - let instance = Private(Provider); + const instance = Private(Provider); expect(instance).to.be(football); }); @@ -25,25 +25,25 @@ describe('Private module loader', function () { return Private; } - let instance = Private(Provider); + const instance = Private(Provider); expect(instance).to.be(Private); }); it('detects circular dependencies', function () { expect(function () { function Provider1() { - let p3 = Private(Provider3); + const p3 = Private(Provider3); } function Provider2() { - let p3 = Private(Provider3); + const p3 = Private(Provider3); } function Provider3() { - let p1 = Private(Provider3); + const p1 = Private(Provider3); } - let p1 = Private(Provider1); + const p1 = Private(Provider1); }).to.throwException(/circular/i); }); @@ -57,24 +57,24 @@ describe('Private module loader', function () { describe('#stub', function () { it('accepts a replacement instance for a Provider', function () { - let replaced = {}; - let replacement = {}; + const replaced = {}; + const replacement = {}; function Provider() { return replaced; } - let instance = Private(Provider); + const instance = Private(Provider); expect(instance).to.be(replaced); Private.stub(Provider, replacement); - let instance2 = Private(Provider); + const instance2 = Private(Provider); expect(instance2).to.be(replacement); Private.stub(Provider, replaced); - let instance3 = Private(Provider); + const instance3 = Private(Provider); expect(instance3).to.be(replaced); }); }); @@ -89,18 +89,18 @@ describe('Private module loader', function () { return {}; } - let instance1 = Private(Provider1); + const instance1 = Private(Provider1); expect(instance1).to.be.an('object'); Private.swap(Provider1, Provider2); - let instance2 = Private(Provider1); + const instance2 = Private(Provider1); expect(instance2).to.be.an('object'); expect(instance2).to.not.be(instance1); Private.swap(Provider1, Provider1); - let instance3 = Private(Provider1); + const instance3 = Private(Provider1); expect(instance3).to.be(instance1); }); @@ -115,12 +115,12 @@ describe('Private module loader', function () { }; } - let instance1 = Private(Provider1); + const instance1 = Private(Provider1); expect(instance1).to.be.an('object'); Private.swap(Provider1, Provider2); - let instance2 = Private(Provider1); + const instance2 = Private(Provider1); expect(instance2).to.have.property('instance1'); expect(instance2.instance1).to.be(instance1); }); diff --git a/src/ui/public/private/private.js b/src/ui/public/private/private.js index 176561512c4cd..58f25198aeda7 100644 --- a/src/ui/public/private/private.js +++ b/src/ui/public/private/private.js @@ -87,7 +87,7 @@ import uiModules from 'ui/modules'; */ -let nextId = _.partial(_.uniqueId, 'privateProvider#'); +const nextId = _.partial(_.uniqueId, 'privateProvider#'); function name(fn) { return fn.name || fn.toString().split('\n').shift(); @@ -95,11 +95,11 @@ function name(fn) { uiModules.get('kibana') .provider('Private', function () { - let provider = this; + const provider = this; // one cache/swaps per Provider - let cache = {}; - let swaps = {}; + const cache = {}; + const swaps = {}; // return the uniq id for this function function identify(fn) { @@ -117,15 +117,15 @@ uiModules.get('kibana') }; provider.swap = function (fn, prov) { - let id = identify(fn); + const id = identify(fn); swaps[id] = prov; }; provider.$get = ['$injector', function PrivateFactory($injector) { // prevent circular deps by tracking where we came from - let privPath = []; - let pathToString = function () { + const privPath = []; + const pathToString = function () { return privPath.map(name).join(' -> '); }; @@ -140,7 +140,7 @@ uiModules.get('kibana') privPath.push(prov); - let context = {}; + const context = {}; let instance = $injector.invoke(prov, context, locals); if (!_.isObject(instance)) instance = context; diff --git a/src/ui/public/promises/__tests__/promises.js b/src/ui/public/promises/__tests__/promises.js index 9ded576e76cf3..f623e54da5f64 100644 --- a/src/ui/public/promises/__tests__/promises.js +++ b/src/ui/public/promises/__tests__/promises.js @@ -31,8 +31,8 @@ describe('Promise service', function () { }); it('rejects if the callback receives an error', function () { - let errback = sinon.stub(); - let err = new Error(); + const errback = sinon.stub(); + const err = new Error(); Promise.fromNode(cb => cb(err)).catch(errback); $rootScope.$apply(); @@ -41,8 +41,8 @@ describe('Promise service', function () { }); it('resolves with the second argument', function () { - let thenback = sinon.stub(); - let result = {}; + const thenback = sinon.stub(); + const result = {}; Promise.fromNode(cb => cb(null, result)).then(thenback); $rootScope.$apply(); @@ -51,9 +51,9 @@ describe('Promise service', function () { }); it('resolves with an array if multiple arguments are received', function () { - let thenback = sinon.stub(); - let result1 = {}; - let result2 = {}; + const thenback = sinon.stub(); + const result1 = {}; + const result2 = {}; Promise.fromNode(cb => cb(null, result1, result2)).then(thenback); $rootScope.$apply(); @@ -63,7 +63,7 @@ describe('Promise service', function () { }); it('resolves with an array if multiple undefined are received', function () { - let thenback = sinon.stub(); + const thenback = sinon.stub(); Promise.fromNode(cb => cb(null, undefined, undefined)).then(thenback); $rootScope.$apply(); diff --git a/src/ui/public/promises/promises.js b/src/ui/public/promises/promises.js index a2d1ef5249c28..8e3ed9c0b3f17 100644 --- a/src/ui/public/promises/promises.js +++ b/src/ui/public/promises/promises.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana'); +const module = uiModules.get('kibana'); // Provides a tiny subset of the excelent API from // bluebird, reimplemented using the $q service @@ -9,7 +9,7 @@ module.service('Promise', function ($q, $timeout) { function Promise(fn) { if (typeof this === 'undefined') throw new Error('Promise constructor must be called with "new"'); - let defer = $q.defer(); + const defer = $q.defer(); try { fn(defer.resolve, defer.reject); } catch (e) { @@ -20,12 +20,12 @@ module.service('Promise', function ($q, $timeout) { Promise.all = Promise.props = $q.all; Promise.resolve = function (val) { - let defer = $q.defer(); + const defer = $q.defer(); defer.resolve(val); return defer.promise; }; Promise.reject = function (reason) { - let defer = $q.defer(); + const defer = $q.defer(); defer.reject(reason); return defer.promise; }; @@ -36,7 +36,7 @@ module.service('Promise', function ($q, $timeout) { }; Promise.method = function (fn) { return function () { - let args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); return Promise.try(fn, args, this); }; }; @@ -51,7 +51,7 @@ module.service('Promise', function ($q, $timeout) { })); }; Promise.each = function (arr, fn) { - let queue = arr.slice(0); + const queue = arr.slice(0); let i = 0; return (function next() { if (!queue.length) return arr; @@ -64,7 +64,7 @@ module.service('Promise', function ($q, $timeout) { return obj && typeof obj.then === 'function'; }; Promise.halt = _.once(function () { - let promise = new Promise(); + const promise = new Promise(); promise.then = _.constant(promise); promise.catch = _.constant(promise); return promise; @@ -155,7 +155,7 @@ module.factory('PromiseEmitter', function (Promise) { * @return {Promise} */ function PromiseEmitter(fn, handler) { - let prom = new Promise(fn); + const prom = new Promise(fn); if (!handler) return prom; diff --git a/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js b/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js index 576fa9f0bd9ae..1b1f8bafba505 100644 --- a/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js +++ b/src/ui/public/reflow_watcher/__tests__/reflow_watcher.js @@ -8,11 +8,11 @@ import EventsProvider from 'ui/events'; import ReflowWatcherProvider from 'ui/reflow_watcher'; describe('Reflow watcher', function () { - let $body = $(document.body); - let $window = $(window); - let expectStubbedEventAndEl = function (stub, event, $el) { + const $body = $(document.body); + const $window = $(window); + const expectStubbedEventAndEl = function (stub, event, $el) { expect(stub.getCalls().some(function (call) { - let events = call.args[0].split(' '); + const events = call.args[0].split(' '); return _.contains(events, event) && $el.is(call.thisValue); })).to.be(true); }; @@ -70,7 +70,7 @@ describe('Reflow watcher', function () { }); it('triggers the "reflow" event within a new angular tick', function () { - let stub = sinon.stub(); + const stub = sinon.stub(); reflowWatcher.on('reflow', stub); reflowWatcher.trigger(); diff --git a/src/ui/public/reflow_watcher/reflow_watcher.js b/src/ui/public/reflow_watcher/reflow_watcher.js index 2592cc9e4bc12..d825e94d9c7e5 100644 --- a/src/ui/public/reflow_watcher/reflow_watcher.js +++ b/src/ui/public/reflow_watcher/reflow_watcher.js @@ -4,12 +4,12 @@ import _ from 'lodash'; import EventsProvider from 'ui/events'; export default function ReflowWatcherService(Private, $rootScope, $http) { - let EventEmitter = Private(EventsProvider); - let $body = $(document.body); - let $window = $(window); + const EventEmitter = Private(EventsProvider); + const $body = $(document.body); + const $window = $(window); - let MOUSE_EVENTS = 'mouseup'; - let WINDOW_EVENTS = 'resize'; + const MOUSE_EVENTS = 'mouseup'; + const WINDOW_EVENTS = 'resize'; _.class(ReflowWatcher).inherits(EventEmitter); /** diff --git a/src/ui/public/registry/__tests__/index.js b/src/ui/public/registry/__tests__/index.js index 85091d32bc754..aaf1f69b115b5 100644 --- a/src/ui/public/registry/__tests__/index.js +++ b/src/ui/public/registry/__tests__/index.js @@ -13,14 +13,14 @@ describe('Registry', function () { })); it('is technically a function', function () { - let reg = registry(); + const reg = registry(); expect(reg).to.be.a('function'); }); describe('#register', function () { it('accepts a Private module', function () { - let reg = registry(); - let mod = function SomePrivateModule() {}; + const reg = registry(); + const mod = function SomePrivateModule() {}; reg.register(mod); // modules are not exposed, so this is the most that we can test @@ -29,13 +29,13 @@ describe('Registry', function () { describe('as a module', function () { it('exposes the list of registered modules', function () { - let reg = registry(); - let mod = function SomePrivateModule(Private) { + const reg = registry(); + const mod = function SomePrivateModule(Private) { this.PrivateModuleLoader = Private; }; reg.register(mod); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.have.length(1); expect(modules[0]).to.have.property('PrivateModuleLoader', Private); }); @@ -43,16 +43,16 @@ describe('Registry', function () { describe('spec', function () { it('executes with the module list as "this", and can override it', function () { - let i = 0; + const i = 0; let self; - let reg = registry({ + const reg = registry({ constructor: function () { return { mods: (self = this) }; } }); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.be.an('object'); expect(modules).to.have.property('mods', self); }); @@ -60,7 +60,7 @@ describe('Registry', function () { describe('spec.name', function () { it('sets the displayName of the registry and the name param on the final instance', function () { - let reg = registry({ + const reg = registry({ name: 'visTypes' }); @@ -72,27 +72,27 @@ describe('Registry', function () { describe('spec.constructor', function () { it('executes before the modules are returned', function () { let i = 0; - let reg = registry({ + const reg = registry({ constructor: function () { i = i + 1; } }); - let modules = Private(reg); + const modules = Private(reg); expect(i).to.be(1); }); it('executes with the module list as "this", and can override it', function () { - let i = 0; + const i = 0; let self; - let reg = registry({ + const reg = registry({ constructor: function () { return { mods: (self = this) }; } }); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.be.an('object'); expect(modules).to.have.property('mods', self); }); @@ -100,13 +100,13 @@ describe('Registry', function () { describe('spec[any]', function () { it('mixes the extra properties into the module list', function () { - let reg = registry({ + const reg = registry({ someMethod: function () { return this; } }); - let modules = Private(reg); + const modules = Private(reg); expect(modules).to.have.property('someMethod'); expect(modules.someMethod()).to.be(modules); }); diff --git a/src/ui/public/registry/_registry.js b/src/ui/public/registry/_registry.js index 396ad08237ed8..c5aa8ec454bc2 100644 --- a/src/ui/public/registry/_registry.js +++ b/src/ui/public/registry/_registry.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexedArray from 'ui/indexed_array'; import RegistryVisTypesProvider from 'ui/registry/vis_types'; -let notPropsOptNames = IndexedArray.OPT_NAMES.concat('constructor'); +const notPropsOptNames = IndexedArray.OPT_NAMES.concat('constructor'); /** * Create a registry, which is just a Private module provider. @@ -49,10 +49,10 @@ let notPropsOptNames = IndexedArray.OPT_NAMES.concat('constructor'); export default function createRegistry(spec) { spec = spec || {}; - let constructor = _.has(spec, 'constructor') && spec.constructor; - let iaOpts = _.defaults(_.pick(spec, IndexedArray.OPT_NAMES), { index: ['name'] }); - let props = _.omit(spec, notPropsOptNames); - let providers = []; + const constructor = _.has(spec, 'constructor') && spec.constructor; + const iaOpts = _.defaults(_.pick(spec, IndexedArray.OPT_NAMES), { index: ['name'] }); + const props = _.omit(spec, notPropsOptNames); + const providers = []; /** * This is the Private module that will be instanciated by @@ -62,7 +62,7 @@ export default function createRegistry(spec) { * that were registered, the registry spec * defines how things will be indexed. */ - let registry = function (Private, $injector) { + const registry = function (Private, $injector) { // index all of the modules iaOpts.initialSet = providers.map(Private); let modules = new IndexedArray(iaOpts); diff --git a/src/ui/public/registry/field_formats.js b/src/ui/public/registry/field_formats.js index ca7895faca82f..393f2660afb47 100644 --- a/src/ui/public/registry/field_formats.js +++ b/src/ui/public/registry/field_formats.js @@ -7,7 +7,7 @@ export default uiRegistry({ group: ['fieldType'], constructor: function (config) { - let self = this; + const self = this; let defaultMap; function init() { @@ -54,7 +54,7 @@ export default uiRegistry({ * @return {FieldFormat} */ self.getInstance = _.memoize(function (formatId) { - let FieldFormat = self.byId[formatId]; + const FieldFormat = self.byId[formatId]; return new FieldFormat(); }); @@ -65,8 +65,8 @@ export default uiRegistry({ * @return {FieldFormat} */ self.getDefaultInstance = _.memoize(function (fieldType) { - let conf = self.getDefaultConfig(fieldType); - let FieldFormat = self.byId[conf.id]; + const conf = self.getDefaultConfig(fieldType); + const FieldFormat = self.byId[conf.id]; return new FieldFormat(conf.params); }); diff --git a/src/ui/public/routes/__tests__/_route_manager.js b/src/ui/public/routes/__tests__/_route_manager.js index c854d88325400..b920e5d63dd14 100644 --- a/src/ui/public/routes/__tests__/_route_manager.js +++ b/src/ui/public/routes/__tests__/_route_manager.js @@ -5,7 +5,7 @@ import RouteManager from 'ui/routes/route_manager'; import expect from 'expect.js'; let routes; // will contain an new instance of RouteManager for each test -let chainableMethods = [ +const chainableMethods = [ { name: 'when', args: ['', {}] }, { name: 'otherwise', args: [{}] }, { name: 'defaults', args: [/regexp/, {}] } @@ -31,7 +31,7 @@ describe('routes/route_manager', function () { describe('#otherwise', function () { it('should forward the last otherwise route', function () { - let otherRoute = {}; + const otherRoute = {}; routes.otherwise({}); routes.otherwise(otherRoute); @@ -68,7 +68,7 @@ describe('routes/route_manager', function () { describe('#config', function () { it('should add defined routes to the global $routeProvider service in order', function () { - let args = [ + const args = [ ['/one', {}], ['/two', {}] ]; @@ -81,8 +81,8 @@ describe('routes/route_manager', function () { expect($rp.when.callCount).to.be(args.length); _.times(args.length, function (i) { - let call = $rp.when.getCall(i); - let a = args.shift(); + const call = $rp.when.getCall(i); + const a = args.shift(); expect(call.args[0]).to.be(a[0]); expect(call.args[1]).to.be(a[1]); diff --git a/src/ui/public/routes/__tests__/_work_queue.js b/src/ui/public/routes/__tests__/_work_queue.js index 863f7345075bd..33044daeae835 100644 --- a/src/ui/public/routes/__tests__/_work_queue.js +++ b/src/ui/public/routes/__tests__/_work_queue.js @@ -25,10 +25,10 @@ describe('work queue', function () { describe('#resolveWhenFull', function () { it('resolves requests waiting for the queue to fill when appropriate', function () { - let size = _.random(5, 50); + const size = _.random(5, 50); queue.limit = size; - let whenFull = Promise.defer(); + const whenFull = Promise.defer(); sinon.stub(whenFull, 'resolve'); queue.resolveWhenFull(whenFull); @@ -53,11 +53,11 @@ describe('work queue', function () { * can manipulate the filled queue */ function fillWithStubs(then) { - let size = _.random(5, 50); - let stub = sinon.stub(); + const size = _.random(5, 50); + const stub = sinon.stub(); _.times(size, function () { - let d = Promise.defer(); + const d = Promise.defer(); // overwrite the defer methods with the stub d.resolve = stub; d.reject = stub; diff --git a/src/ui/public/routes/__tests__/_wrap_route_with_prep.js b/src/ui/public/routes/__tests__/_wrap_route_with_prep.js index a56cb503e1d46..8570b3f7cb8c3 100644 --- a/src/ui/public/routes/__tests__/_wrap_route_with_prep.js +++ b/src/ui/public/routes/__tests__/_wrap_route_with_prep.js @@ -18,11 +18,11 @@ describe('wrapRouteWithPrep fn', function () { routes = new RouteManager(); }); - let SchedulingTest = function (opts) { + const SchedulingTest = function (opts) { opts = opts || {}; - let delaySetup = opts.delayUserWork ? 0 : 50; - let delayUserWork = opts.delayUserWork ? 50 : 0; + const delaySetup = opts.delayUserWork ? 0 : 50; + const delayUserWork = opts.delayUserWork ? 50 : 0; return function () { ngMock.module('kibana', 'kibana/notify'); diff --git a/src/ui/public/routes/route_manager.js b/src/ui/public/routes/route_manager.js index e06c9fc6e55d5..22c6c1e518387 100644 --- a/src/ui/public/routes/route_manager.js +++ b/src/ui/public/routes/route_manager.js @@ -4,16 +4,16 @@ import wrapRouteWithPrep from './wrap_route_with_prep'; import RouteSetupManager from './route_setup_manager'; function RouteManager() { - let self = this; - let setup = new RouteSetupManager(); - let when = []; - let defaults = []; + const self = this; + const setup = new RouteSetupManager(); + const when = []; + const defaults = []; let otherwise; self.config = function ($routeProvider) { when.forEach(function (args) { - let path = args[0]; - let route = args[1] || {}; + const path = args[0]; + const route = args[1] || {}; // merge in any defaults defaults.forEach(function (args) { @@ -40,7 +40,7 @@ function RouteManager() { } }; - let wrapSetupAndChain = (fn, ...args) => { + const wrapSetupAndChain = (fn, ...args) => { fn.apply(setup, args); return this; }; diff --git a/src/ui/public/routes/route_setup_manager.js b/src/ui/public/routes/route_setup_manager.js index 1cb89fe456455..15ab1b264149f 100644 --- a/src/ui/public/routes/route_setup_manager.js +++ b/src/ui/public/routes/route_setup_manager.js @@ -30,7 +30,7 @@ module.exports = class RouteSetupManager { */ doWork(Promise, $injector, userWork) { - let invokeEach = (arr, locals) => { + const invokeEach = (arr, locals) => { return Promise.map(arr, fn => { if (!fn) return; return $injector.invoke(fn, null, locals); @@ -39,16 +39,16 @@ module.exports = class RouteSetupManager { // call each error handler in order, until one of them resolves // or we run out of handlers - let callErrorHandlers = (handlers, origError) => { + const callErrorHandlers = (handlers, origError) => { if (!_.size(handlers)) throw origError; // clone so we don't discard handlers or loose them handlers = handlers.slice(0); - let next = (err) => { + const next = (err) => { if (!handlers.length) throw err; - let handler = handlers.shift(); + const handler = handlers.shift(); if (!handler) return next(err); return Promise.try(function () { @@ -66,7 +66,7 @@ module.exports = class RouteSetupManager { ) .then(() => { // wait for the queue to fill up, then do all the work - let defer = Promise.defer(); + const defer = Promise.defer(); userWork.resolveWhenFull(defer); return defer.promise.then(() => Promise.all(userWork.doWork())); diff --git a/src/ui/public/routes/routes.js b/src/ui/public/routes/routes.js index cbb9878df7a1e..077590cafa642 100644 --- a/src/ui/public/routes/routes.js +++ b/src/ui/public/routes/routes.js @@ -1,7 +1,7 @@ import RouteManager from './route_manager'; import 'angular-route/angular-route'; import uiModules from 'ui/modules'; -let defaultRouteManager = new RouteManager(); +const defaultRouteManager = new RouteManager(); module.exports = { ...defaultRouteManager, diff --git a/src/ui/public/routes/work_queue.js b/src/ui/public/routes/work_queue.js index 40f4294327829..05146f6613a07 100644 --- a/src/ui/public/routes/work_queue.js +++ b/src/ui/public/routes/work_queue.js @@ -1,10 +1,10 @@ import _ from 'lodash'; function WorkQueue() { - let q = this; + const q = this; - let work = []; - let fullDefers = []; + const work = []; + const fullDefers = []; q.limit = 0; Object.defineProperty(q, 'length', { @@ -13,13 +13,13 @@ function WorkQueue() { } }); - let resolve = function (defers) { + const resolve = function (defers) { return defers.splice(0).map(function (defer) { return defer.resolve(); }); }; - let checkIfFull = function () { + const checkIfFull = function () { if (work.length >= q.limit && fullDefers.length) { resolve(fullDefers); } @@ -31,7 +31,7 @@ function WorkQueue() { }; q.doWork = function () { - let resps = resolve(work); + const resps = resolve(work); checkIfFull(); return resps; }; diff --git a/src/ui/public/routes/wrap_route_with_prep.js b/src/ui/public/routes/wrap_route_with_prep.js index 5c4b98a82d0a8..6ed3368226af3 100644 --- a/src/ui/public/routes/wrap_route_with_prep.js +++ b/src/ui/public/routes/wrap_route_with_prep.js @@ -7,11 +7,11 @@ import errors from 'ui/errors'; function wrapRouteWithPrep(route, setup) { if (!route.resolve && route.redirectTo) return; - let userWork = new WorkQueue(); + const userWork = new WorkQueue(); // the point at which we will consider the queue "full" userWork.limit = _.keys(route.resolve).length; - let resolve = { + const resolve = { __prep__: function ($injector) { return $injector.invoke(setup.doWork, setup, { userWork }); } @@ -21,7 +21,7 @@ function wrapRouteWithPrep(route, setup) { // prep is complete _.forOwn(route.resolve || {}, function (expr, name) { resolve[name] = function ($injector, Promise) { - let defer = Promise.defer(); + const defer = Promise.defer(); userWork.push(defer); return defer.promise.then(function () { return $injector[angular.isString(expr) ? 'get' : 'invoke'](expr); diff --git a/src/ui/public/state_management/__tests__/app_state.js b/src/ui/public/state_management/__tests__/app_state.js index 6f9af310db4a4..ba4b1310a0f70 100644 --- a/src/ui/public/state_management/__tests__/app_state.js +++ b/src/ui/public/state_management/__tests__/app_state.js @@ -27,7 +27,7 @@ describe('State Management', function () { }); it('should use passed in params', function () { - let params = { + const params = { test: true, mock: false }; @@ -46,8 +46,8 @@ describe('State Management', function () { }); it('should be destroyed on $routeChangeStart', function () { - let destroySpy = sinon.spy(appState, 'destroy'); - let url = '/test/path'; + const destroySpy = sinon.spy(appState, 'destroy'); + const url = '/test/path'; $rootScope.$emit('$routeChangeStart'); diff --git a/src/ui/public/state_management/__tests__/state.js b/src/ui/public/state_management/__tests__/state.js index ae8153f0d326d..75a374db7c717 100644 --- a/src/ui/public/state_management/__tests__/state.js +++ b/src/ui/public/state_management/__tests__/state.js @@ -53,7 +53,7 @@ describe('State Management', function () { it('should reset the state to the defaults', function () { const { state, getUnhashedSearch } = setup({ initial: { message: ['test'] } }); state.reset(); - let search = getUnhashedSearch(state); + const search = getUnhashedSearch(state); expect(search).to.have.property('_s'); expect(search._s).to.equal('(message:!(test))'); expect(state.message).to.eql(['test']); @@ -97,7 +97,7 @@ describe('State Management', function () { it('should save to $location.search()', function () { const { state, getUnhashedSearch } = setup({ initial: { test: 'foo' } }); state.save(); - let search = getUnhashedSearch(state); + const search = getUnhashedSearch(state); expect(search).to.have.property('_s'); expect(search._s).to.equal('(test:foo)'); }); @@ -160,7 +160,7 @@ describe('State Management', function () { it('should call fetch when $routeUpdate is fired on $rootScope', function () { const { state } = setup(); - let spy = sinon.spy(state, 'fetch'); + const spy = sinon.spy(state, 'fetch'); $rootScope.$emit('$routeUpdate', 'test'); sinon.assert.calledOnce(spy); }); diff --git a/src/ui/public/state_management/app_state.js b/src/ui/public/state_management/app_state.js index 903071a723677..533b273d70dcb 100644 --- a/src/ui/public/state_management/app_state.js +++ b/src/ui/public/state_management/app_state.js @@ -12,11 +12,11 @@ import _ from 'lodash'; import modules from 'ui/modules'; import StateManagementStateProvider from 'ui/state_management/state'; import PersistedStatePersistedStateProvider from 'ui/persisted_state/persisted_state'; -let urlParam = '_a'; +const urlParam = '_a'; function AppStateProvider(Private, $rootScope, $location) { - let State = Private(StateManagementStateProvider); - let PersistedState = Private(PersistedStatePersistedStateProvider); + const State = Private(StateManagementStateProvider); + const PersistedState = Private(PersistedStatePersistedStateProvider); let persistedStates; let eventUnsubscribers; @@ -49,31 +49,31 @@ function AppStateProvider(Private, $rootScope, $location) { */ AppState.prototype.makeStateful = function (prop) { if (persistedStates[prop]) return persistedStates[prop]; - let self = this; + const self = this; // set up the ui state persistedStates[prop] = new PersistedState(); // update the app state when the stateful instance changes - let updateOnChange = function () { - let replaceState = false; // TODO: debouncing logic + const updateOnChange = function () { + const replaceState = false; // TODO: debouncing logic self[prop] = persistedStates[prop].getChanges(); // Save state to the URL. self.save(replaceState); }; - let handlerOnChange = (method) => persistedStates[prop][method]('change', updateOnChange); + const handlerOnChange = (method) => persistedStates[prop][method]('change', updateOnChange); handlerOnChange('on'); eventUnsubscribers.push(() => handlerOnChange('off')); // update the stateful object when the app state changes - let persistOnChange = function (changes) { + const persistOnChange = function (changes) { if (!changes) return; if (changes.indexOf(prop) !== -1) { persistedStates[prop].set(self[prop]); } }; - let handlePersist = (method) => this[method]('fetch_with_changes', persistOnChange); + const handlePersist = (method) => this[method]('fetch_with_changes', persistOnChange); handlePersist('on'); eventUnsubscribers.push(() => handlePersist('off')); @@ -92,7 +92,7 @@ function AppStateProvider(Private, $rootScope, $location) { // Checks to see if the appState might already exist, even if it hasn't been newed up get.previouslyStored = function () { - let search = $location.search(); + const search = $location.search(); return search[urlParam] ? true : false; }; diff --git a/src/ui/public/state_management/global_state.js b/src/ui/public/state_management/global_state.js index 7448822d7b8b8..81c875b086a6f 100644 --- a/src/ui/public/state_management/global_state.js +++ b/src/ui/public/state_management/global_state.js @@ -5,10 +5,10 @@ import rison from 'rison-node'; import StateManagementStateProvider from 'ui/state_management/state'; import uiModules from 'ui/modules'; -let module = uiModules.get('kibana/global_state'); +const module = uiModules.get('kibana/global_state'); function GlobalStateProvider(Private, $rootScope, $location) { - let State = Private(StateManagementStateProvider); + const State = Private(StateManagementStateProvider); _.class(GlobalState).inherits(State); function GlobalState(defaults) { diff --git a/src/ui/public/state_management/state.js b/src/ui/public/state_management/state.js index 5dc113ecc6faa..2380db54de1a7 100644 --- a/src/ui/public/state_management/state.js +++ b/src/ui/public/state_management/state.js @@ -121,7 +121,7 @@ export default function StateProvider(Private, $rootScope, $location, config) { _.defaults(stash, this._defaults); // apply diff to state from stash, will change state in place via side effect - let diffResults = applyDiff(this, stash); + const diffResults = applyDiff(this, stash); if (diffResults.keys.length) { this.emit('fetch_with_changes', diffResults.keys); @@ -134,7 +134,7 @@ export default function StateProvider(Private, $rootScope, $location, config) { */ State.prototype.save = function (replace) { let stash = this._readFromURL(); - let state = this.toObject(); + const state = this.toObject(); replace = replace || false; if (!stash) { @@ -143,14 +143,14 @@ export default function StateProvider(Private, $rootScope, $location, config) { } // apply diff to state from stash, will change state in place via side effect - let diffResults = applyDiff(stash, _.defaults({}, state, this._defaults)); + const diffResults = applyDiff(stash, _.defaults({}, state, this._defaults)); if (diffResults.keys.length) { this.emit('save_with_changes', diffResults.keys); } // persist the state in the URL - let search = $location.search(); + const search = $location.search(); search[this._urlParam] = this.toQueryParam(state); if (replace) { $location.search(search).replace(); @@ -175,7 +175,7 @@ export default function StateProvider(Private, $rootScope, $location, config) { State.prototype.reset = function () { // apply diff to _attributes from defaults, this is side effecting so // it will change the state in place. - let diffResults = applyDiff(this, this._defaults); + const diffResults = applyDiff(this, this._defaults); if (diffResults.keys.length) { this.emit('reset_with_changes', diffResults.keys); } diff --git a/src/ui/public/storage/__tests__/storage.js b/src/ui/public/storage/__tests__/storage.js index 8a4d5e2872f7c..f5f5f7a7c425c 100644 --- a/src/ui/public/storage/__tests__/storage.js +++ b/src/ui/public/storage/__tests__/storage.js @@ -5,7 +5,7 @@ import 'ui/storage'; let storage; let $window; -let payload = { first: 'john', last: 'smith' }; +const payload = { first: 'john', last: 'smith' }; function init() { @@ -69,21 +69,21 @@ describe('StorageService', function () { describe('json data', function () { it('should parse JSON when reading from the store', function () { - let getItem = $window.localStorage.getItem; + const getItem = $window.localStorage.getItem; getItem.returns(JSON.stringify(payload)); - let data = storage.get('name'); + const data = storage.get('name'); expect(data).to.eql(payload); }); it('should write JSON string to the store', function () { - let setItem = $window.localStorage.setItem; - let key = 'name'; - let value = payload; + const setItem = $window.localStorage.setItem; + const key = 'name'; + const value = payload; storage.set(key, value); - let call = setItem.getCall(0); + const call = setItem.getCall(0); expect(call.args[0]).to.equal(key); expect(call.args[1]).to.equal(JSON.stringify(value)); }); @@ -91,15 +91,15 @@ describe('StorageService', function () { describe('expected responses', function () { it('should return null when not exists', function () { - let data = storage.get('notexists'); + const data = storage.get('notexists'); expect(data).to.equal(null); }); it('should return null when invalid JSON', function () { - let getItem = $window.localStorage.getItem; + const getItem = $window.localStorage.getItem; getItem.returns('not: json'); - let data = storage.get('name'); + const data = storage.get('name'); expect(data).to.equal(null); }); }); diff --git a/src/ui/public/storage/storage.js b/src/ui/public/storage/storage.js index aa043158724bd..eaa243ed5be1d 100644 --- a/src/ui/public/storage/storage.js +++ b/src/ui/public/storage/storage.js @@ -2,7 +2,7 @@ import modules from 'ui/modules'; import angular from 'angular'; function Storage(store) { - let self = this; + const self = this; self.store = store; self.get = function (key) { @@ -30,7 +30,7 @@ function Storage(store) { }; } -let createService = function (type) { +const createService = function (type) { return function ($window) { return new Storage($window[type]); }; diff --git a/src/ui/public/stringify/__tests__/_color.js b/src/ui/public/stringify/__tests__/_color.js index 98686bacc3148..05e3021dc902a 100644 --- a/src/ui/public/stringify/__tests__/_color.js +++ b/src/ui/public/stringify/__tests__/_color.js @@ -13,7 +13,7 @@ describe('Color Format', function () { context('field is a number', () => { it('should add colors if the value is in range', function () { - let colorer = new ColorFormat({ + const colorer = new ColorFormat({ fieldType: 'number', colors: [{ range: '100:150', @@ -28,7 +28,7 @@ describe('Color Format', function () { }); it('should not convert invalid ranges', function () { - let colorer = new ColorFormat({ + const colorer = new ColorFormat({ fieldType: 'number', colors: [{ range: '100150', @@ -42,7 +42,7 @@ describe('Color Format', function () { context('field is a string', () => { it('should add colors if the regex matches', function () { - let colorer = new ColorFormat({ + const colorer = new ColorFormat({ fieldType: 'string', colors: [{ regex: 'A.*', @@ -51,7 +51,7 @@ describe('Color Format', function () { }] }); - let converter = colorer.getConverterFor('html'); + const converter = colorer.getConverterFor('html'); expect(converter('B', 'html')).to.eql('B'); expect(converter('AAA', 'html')).to.eql('AAA'); expect(converter('AB', 'html')).to.eql('AB'); diff --git a/src/ui/public/stringify/__tests__/_date.js b/src/ui/public/stringify/__tests__/_date.js index aec730580bf48..c3a90a2c1d7f1 100644 --- a/src/ui/public/stringify/__tests__/_date.js +++ b/src/ui/public/stringify/__tests__/_date.js @@ -15,8 +15,8 @@ describe('Date Format', function () { settings = config; fieldFormats = Private(RegistryFieldFormatsProvider); - let DateFormat = fieldFormats.getType('date'); - let date = new DateFormat(); + const DateFormat = fieldFormats.getType('date'); + const date = new DateFormat(); convert = date.convert.bind(date); })); @@ -30,17 +30,17 @@ describe('Date Format', function () { function setDefaultTimezone() { moment.tz.setDefault(settings.get('dateFormat:tz')); } - let time = 1445027693942; + const time = 1445027693942; off = $scope.$on('change:config.dateFormat:tz', setDefaultTimezone); settings.set('dateFormat:tz', 'America/Chicago'); $scope.$digest(); - let chicagoTime = convert(time); + const chicagoTime = convert(time); settings.set('dateFormat:tz', 'America/Phoenix'); $scope.$digest(); - let phoenixTime = convert(time); + const phoenixTime = convert(time); expect(chicagoTime).not.to.equal(phoenixTime); off(); diff --git a/src/ui/public/stringify/__tests__/_source.js b/src/ui/public/stringify/__tests__/_source.js index 63d4691c33b09..38806c03dbed0 100644 --- a/src/ui/public/stringify/__tests__/_source.js +++ b/src/ui/public/stringify/__tests__/_source.js @@ -28,8 +28,8 @@ describe('_source formatting', function () { })); it('uses the _source, field, and hit to create a
', function () { - let hit = _.first(hits); - let $dl = $(convertHtml(hit._source, indexPattern.fields.byName._source, hit)); + const hit = _.first(hits); + const $dl = $(convertHtml(hit._source, indexPattern.fields.byName._source, hit)); expect($dl.is('dl')).to.be.ok(); expect($dl.find('dt')).to.have.length(_.keys(indexPattern.flattenHit(hit)).length); }); diff --git a/src/ui/public/stringify/__tests__/_string.js b/src/ui/public/stringify/__tests__/_string.js index f0b4b254db15e..19212e23b6670 100644 --- a/src/ui/public/stringify/__tests__/_string.js +++ b/src/ui/public/stringify/__tests__/_string.js @@ -10,16 +10,16 @@ describe('String Format', function () { })); it('decode a base64 string', function () { - let StringFormat = fieldFormats.getType('string'); - let string = new StringFormat({ + const StringFormat = fieldFormats.getType('string'); + const string = new StringFormat({ transform: 'base64' }); expect(string.convert('Zm9vYmFy')).to.be('foobar'); }); it('convert a string to title case', function () { - let StringFormat = fieldFormats.getType('string'); - let string = new StringFormat({ + const StringFormat = fieldFormats.getType('string'); + const string = new StringFormat({ transform: 'title' }); expect(string.convert('PLEASE DO NOT SHOUT')).to.be('Please Do Not Shout'); diff --git a/src/ui/public/stringify/__tests__/_truncate.js b/src/ui/public/stringify/__tests__/_truncate.js index 7e9564944402a..7f36690b8e1c7 100644 --- a/src/ui/public/stringify/__tests__/_truncate.js +++ b/src/ui/public/stringify/__tests__/_truncate.js @@ -10,29 +10,29 @@ describe('String Truncate Format', function () { })); it('truncate large string', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: 4}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: 4}); expect(truncate.convert('This is some text')).to.be('This...'); }); it('does not truncate large string when field length is not a string', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: 'not number'}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: 'not number'}); expect(truncate.convert('This is some text')).to.be('This is some text'); }); it('does not truncate large string when field length is null', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: null}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: null}); expect(truncate.convert('This is some text')).to.be('This is some text'); }); it('does not truncate large string when field length larger than the text', function () { - let Truncate = fieldFormats.getType('truncate'); - let truncate = new Truncate({fieldLength: 100000}); + const Truncate = fieldFormats.getType('truncate'); + const truncate = new Truncate({fieldLength: 100000}); expect(truncate.convert('This is some text')).to.be('This is some text'); }); diff --git a/src/ui/public/stringify/__tests__/_url.js b/src/ui/public/stringify/__tests__/_url.js index 845ad0fb27885..48a918e67b867 100644 --- a/src/ui/public/stringify/__tests__/_url.js +++ b/src/ui/public/stringify/__tests__/_url.js @@ -19,9 +19,9 @@ describe('Url Format', function () { }); it('ouputs a simple tab by default', function () { - let url = new Url(); + const url = new Url(); - let $a = $(url.convert('http://elastic.co', 'html')); + const $a = $(url.convert('http://elastic.co', 'html')); expect($a.is('a')).to.be(true); expect($a.size()).to.be(1); expect($a.attr('href')).to.be('http://elastic.co'); @@ -30,17 +30,17 @@ describe('Url Format', function () { }); it('outputs an if type === "img"', function () { - let url = new Url({ type: 'img' }); + const url = new Url({ type: 'img' }); - let $img = $(url.convert('http://elastic.co', 'html')); + const $img = $(url.convert('http://elastic.co', 'html')); expect($img.is('img')).to.be(true); expect($img.attr('src')).to.be('http://elastic.co'); }); describe('url template', function () { it('accepts a template', function () { - let url = new Url({ urlTemplate: 'url: {{ value }}' }); - let $a = $(url.convert('url', 'html')); + const url = new Url({ urlTemplate: 'url: {{ value }}' }); + const $a = $(url.convert('url', 'html')); expect($a.is('a')).to.be(true); expect($a.size()).to.be(1); expect($a.attr('href')).to.be('url: url'); @@ -49,15 +49,15 @@ describe('Url Format', function () { }); it('only outputs the url if the contentType === "text"', function () { - let url = new Url(); + const url = new Url(); expect(url.convert('url', 'text')).to.be('url'); }); }); describe('label template', function () { it('accepts a template', function () { - let url = new Url({ labelTemplate: 'extension: {{ value }}' }); - let $a = $(url.convert('php', 'html')); + const url = new Url({ labelTemplate: 'extension: {{ value }}' }); + const $a = $(url.convert('php', 'html')); expect($a.is('a')).to.be(true); expect($a.size()).to.be(1); expect($a.attr('href')).to.be('php'); @@ -65,19 +65,19 @@ describe('Url Format', function () { }); it('uses the label template for text formating', function () { - let url = new Url({ labelTemplate: 'external {{value }}'}); + const url = new Url({ labelTemplate: 'external {{value }}'}); expect(url.convert('url', 'text')).to.be('external url'); }); it('can use the raw value', function () { - let url = new Url({ + const url = new Url({ labelTemplate: 'external {{value}}' }); expect(url.convert('url?', 'text')).to.be('external url?'); }); it('can use the url', function () { - let url = new Url({ + const url = new Url({ urlTemplate: 'http://google.com/{{value}}', labelTemplate: 'external {{url}}' }); @@ -87,19 +87,19 @@ describe('Url Format', function () { describe('templating', function () { it('ignores unknown variables', function () { - let url = new Url({ urlTemplate: '{{ not really a var }}' }); + const url = new Url({ urlTemplate: '{{ not really a var }}' }); expect(url.convert('url', 'text')).to.be(''); }); it('does not allow executing code in variable expressions', function () { window.SHOULD_NOT_BE_TRUE = false; - let url = new Url({ urlTemplate: '{{ (window.SHOULD_NOT_BE_TRUE = true) && value }}' }); + const url = new Url({ urlTemplate: '{{ (window.SHOULD_NOT_BE_TRUE = true) && value }}' }); expect(url.convert('url', 'text')).to.be(''); }); describe('', function () { it('does not get values from the prototype chain', function () { - let url = new Url({ urlTemplate: '{{ toString }}' }); + const url = new Url({ urlTemplate: '{{ toString }}' }); expect(url.convert('url', 'text')).to.be(''); }); }); diff --git a/src/ui/public/stringify/types/_numeral.js b/src/ui/public/stringify/types/_numeral.js index ee55f155b4341..9bbab9715436e 100644 --- a/src/ui/public/stringify/types/_numeral.js +++ b/src/ui/public/stringify/types/_numeral.js @@ -3,9 +3,9 @@ import 'ui/field_format_editor/numeral/numeral'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; import BoundToConfigObjProvider from 'ui/bound_to_config_obj'; export default function AbstractNumeralFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let BoundToConfigObj = Private(BoundToConfigObjProvider); - let numeral = require('numeral')(); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const BoundToConfigObj = Private(BoundToConfigObjProvider); + const numeral = require('numeral')(); _.class(Numeral).inherits(FieldFormat); function Numeral(params) { diff --git a/src/ui/public/stringify/types/boolean.js b/src/ui/public/stringify/types/boolean.js index 651b129ad0783..6c522db02527c 100644 --- a/src/ui/public/stringify/types/boolean.js +++ b/src/ui/public/stringify/types/boolean.js @@ -3,7 +3,7 @@ import _ from 'lodash'; export default function TruncateFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); class Bool extends FieldFormat { diff --git a/src/ui/public/stringify/types/bytes.js b/src/ui/public/stringify/types/bytes.js index 88e72823a4a4c..a585656df150b 100644 --- a/src/ui/public/stringify/types/bytes.js +++ b/src/ui/public/stringify/types/bytes.js @@ -1,7 +1,7 @@ import StringifyTypesNumeralProvider from 'ui/stringify/types/_numeral'; export default function BytesFormatProvider(Private) { - let Numeral = Private(StringifyTypesNumeralProvider); + const Numeral = Private(StringifyTypesNumeralProvider); return Numeral.factory({ id: 'bytes', title: 'Bytes', diff --git a/src/ui/public/stringify/types/date.js b/src/ui/public/stringify/types/date.js index d88ff3ed4d910..b0faef57501a0 100644 --- a/src/ui/public/stringify/types/date.js +++ b/src/ui/public/stringify/types/date.js @@ -5,8 +5,8 @@ import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/fi import BoundToConfigObjProvider from 'ui/bound_to_config_obj'; import dateTemplate from 'ui/stringify/editors/date.html'; export default function DateTimeFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let BoundToConfigObj = Private(BoundToConfigObjProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const BoundToConfigObj = Private(BoundToConfigObjProvider); _.class(DateTime).inherits(FieldFormat); @@ -27,7 +27,7 @@ export default function DateTimeFormatProvider(Private) { template: dateTemplate, controllerAs: 'cntrl', controller: function ($interval, $scope) { - let self = this; + const self = this; self.sampleInputs = [ Date.now(), +moment().startOf('year'), @@ -43,11 +43,11 @@ export default function DateTimeFormatProvider(Private) { DateTime.prototype._convert = function (val) { // don't give away our ref to converter so // we can hot-swap when config changes - let pattern = this.param('pattern'); - let timezone = this.param('timezone'); + const pattern = this.param('pattern'); + const timezone = this.param('timezone'); - let timezoneChanged = this._timeZone !== timezone; - let datePatternChanged = this._memoizedPattern !== pattern; + const timezoneChanged = this._timeZone !== timezone; + const datePatternChanged = this._memoizedPattern !== pattern; if (timezoneChanged || datePatternChanged) { this._timeZone = timezone; this._memoizedPattern = pattern; diff --git a/src/ui/public/stringify/types/ip.js b/src/ui/public/stringify/types/ip.js index 465d77fc3b41e..875c20401afc5 100644 --- a/src/ui/public/stringify/types/ip.js +++ b/src/ui/public/stringify/types/ip.js @@ -1,7 +1,7 @@ import _ from 'lodash'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function IpFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); _.class(Ip).inherits(FieldFormat); function Ip(params) { diff --git a/src/ui/public/stringify/types/number.js b/src/ui/public/stringify/types/number.js index e9d12b1d241f2..569be5cf32bc4 100644 --- a/src/ui/public/stringify/types/number.js +++ b/src/ui/public/stringify/types/number.js @@ -1,7 +1,7 @@ import StringifyTypesNumeralProvider from 'ui/stringify/types/_numeral'; export default function NumberFormatProvider(Private) { - let Numeral = Private(StringifyTypesNumeralProvider); + const Numeral = Private(StringifyTypesNumeralProvider); return Numeral.factory({ id: 'number', title: 'Number', diff --git a/src/ui/public/stringify/types/percent.js b/src/ui/public/stringify/types/percent.js index f309604ef0f0b..d4a2d672a0829 100644 --- a/src/ui/public/stringify/types/percent.js +++ b/src/ui/public/stringify/types/percent.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import BoundToConfigObjProvider from 'ui/bound_to_config_obj'; import StringifyTypesNumeralProvider from 'ui/stringify/types/_numeral'; export default function PercentFormatProvider(Private) { - let BoundToConfigObj = Private(BoundToConfigObjProvider); - let Numeral = Private(StringifyTypesNumeralProvider); + const BoundToConfigObj = Private(BoundToConfigObjProvider); + const Numeral = Private(StringifyTypesNumeralProvider); return Numeral.factory({ id: 'percent', diff --git a/src/ui/public/stringify/types/source.js b/src/ui/public/stringify/types/source.js index 9662bfebef4ec..55fcde64cb491 100644 --- a/src/ui/public/stringify/types/source.js +++ b/src/ui/public/stringify/types/source.js @@ -3,8 +3,8 @@ import noWhiteSpace from 'ui/utils/no_white_space'; import angular from 'angular'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function _SourceFormatProvider(Private, shortDotsFilter) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let template = _.template(noWhiteSpace(require('ui/stringify/types/_source.html'))); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const template = _.template(noWhiteSpace(require('ui/stringify/types/_source.html'))); _.class(Source).inherits(FieldFormat); function Source(params) { @@ -20,15 +20,15 @@ export default function _SourceFormatProvider(Private, shortDotsFilter) { html: function sourceToHtml(source, field, hit) { if (!field) return this.getConverter('text')(source, field, hit); - let highlights = (hit && hit.highlight) || {}; - let formatted = field.indexPattern.formatHit(hit); - let highlightPairs = []; - let sourcePairs = []; + const highlights = (hit && hit.highlight) || {}; + const formatted = field.indexPattern.formatHit(hit); + const highlightPairs = []; + const sourcePairs = []; _.keys(formatted).forEach(function (key) { - let pairs = highlights[key] ? highlightPairs : sourcePairs; - let field = shortDotsFilter(key); - let val = formatted[key]; + const pairs = highlights[key] ? highlightPairs : sourcePairs; + const field = shortDotsFilter(key); + const val = formatted[key]; pairs.push([field, val]); }, []); diff --git a/src/ui/public/stringify/types/string.js b/src/ui/public/stringify/types/string.js index 3db37865534e7..259469706ab68 100644 --- a/src/ui/public/stringify/types/string.js +++ b/src/ui/public/stringify/types/string.js @@ -2,7 +2,7 @@ import _ from 'lodash'; import 'ui/field_format_editor/samples/samples'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function StringFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); _.class(_String).inherits(FieldFormat); diff --git a/src/ui/public/stringify/types/truncate.js b/src/ui/public/stringify/types/truncate.js index 666add8819581..b20a7c2c62092 100644 --- a/src/ui/public/stringify/types/truncate.js +++ b/src/ui/public/stringify/types/truncate.js @@ -2,8 +2,8 @@ import _ from 'lodash'; import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/field_format'; export default function TruncateFormatProvider(Private) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); - let omission = '...'; + const FieldFormat = Private(IndexPatternsFieldFormatProvider); + const omission = '...'; _.class(Truncate).inherits(FieldFormat); @@ -16,7 +16,7 @@ export default function TruncateFormatProvider(Private) { Truncate.fieldType = ['string']; Truncate.prototype._convert = function (val) { - let length = this.param('fieldLength'); + const length = this.param('fieldLength'); if (length > 0) { return _.trunc(val, { 'length': length + omission.length, diff --git a/src/ui/public/stringify/types/url.js b/src/ui/public/stringify/types/url.js index eb1c46aeaaafe..a848567523ed9 100644 --- a/src/ui/public/stringify/types/url.js +++ b/src/ui/public/stringify/types/url.js @@ -5,7 +5,7 @@ import IndexPatternsFieldFormatProvider from 'ui/index_patterns/_field_format/fi import urlTemplate from 'ui/stringify/editors/url.html'; export default function UrlFormatProvider(Private, highlightFilter) { - let FieldFormat = Private(IndexPatternsFieldFormatProvider); + const FieldFormat = Private(IndexPatternsFieldFormatProvider); _.class(Url).inherits(FieldFormat); @@ -31,7 +31,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { template: urlTemplate, controllerAs: 'url', controller: function ($scope) { - let iconPattern = '/bundles/src/ui/public/stringify/icons/{{value}}.png'; + const iconPattern = '/bundles/src/ui/public/stringify/icons/{{value}}.png'; this.samples = { a: [ 'john', '/some/pathname/asset.png', 1234 ], @@ -39,7 +39,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }; $scope.$watch('editor.formatParams.type', function (type, prev) { - let params = $scope.editor.formatParams; + const params = $scope.editor.formatParams; if (type === 'img' && type !== prev && !params.urlTemplate) { params.urlTemplate = iconPattern; } @@ -60,7 +60,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { ]; Url.prototype._formatUrl = function (value) { - let template = this.param('urlTemplate'); + const template = this.param('urlTemplate'); if (!template) return value; return this._compileTemplate(template)({ @@ -70,7 +70,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }; Url.prototype._formatLabel = function (value, url) { - let template = this.param('labelTemplate'); + const template = this.param('labelTemplate'); if (url == null) url = this._formatUrl(value); if (!template) return url; @@ -86,7 +86,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }, html: function (rawValue, field, hit) { - let url = _.escape(this._formatUrl(rawValue)); + const url = _.escape(this._formatUrl(rawValue)); let label = _.escape(this._formatLabel(rawValue, url)); switch (this.param('type')) { @@ -103,7 +103,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { }; Url.prototype._compileTemplate = function (template) { - let parts = template.split(Url.templateMatchRE).map(function (part, i) { + const parts = template.split(Url.templateMatchRE).map(function (part, i) { // trim all the odd bits, the variable names return (i % 2) ? part.trim() : part; }); @@ -115,7 +115,7 @@ export default function UrlFormatProvider(Private, highlightFilter) { while (++i < parts.length) { if (i % 2) { if (locals.hasOwnProperty(parts[i])) { - let local = locals[parts[i]]; + const local = locals[parts[i]]; output += local == null ? '' : local; } } else { diff --git a/src/ui/public/style_compile/__tests__/style_compile.js b/src/ui/public/style_compile/__tests__/style_compile.js index 3bb46d7f3cb27..804e0f0b59287 100644 --- a/src/ui/public/style_compile/__tests__/style_compile.js +++ b/src/ui/public/style_compile/__tests__/style_compile.js @@ -13,7 +13,7 @@ describe('styleCompile directive', function () { })); it('exports a few config values as css', function () { - let $style = $('#style-compile'); + const $style = $('#style-compile'); config.set('truncate:maxHeight', 0); $rootScope.$apply(); diff --git a/src/ui/public/style_compile/style_compile.js b/src/ui/public/style_compile/style_compile.js index 4ec2bd7367c03..90fc2e09fecbd 100644 --- a/src/ui/public/style_compile/style_compile.js +++ b/src/ui/public/style_compile/style_compile.js @@ -2,15 +2,15 @@ import _ from 'lodash'; import $ from 'jquery'; import 'ui/config'; import uiModules from 'ui/modules'; -let $style = $('